pagination in page with custom code in wordpress - wordpress

How to add pagination for comments in page with custom code in Wordpress?
My code:
<?php
<ol class="comment-list">
<?php
$comments = get_comments(array(
'number' => '8',
'status' => 'approve',
'offset' => $offset
));
foreach( $comments as $comment ){
echo $comment->comment_author . '<br />' . $comment->comment_content;
}
?>
</ol>
<?php paginate_comments_links ( array( 'prev_text' => '« PREV' , 'next_text' => 'NEXT »' ) ); ?>
I searched here for solutions, but did not find any. There are old posts from before 2014. Other codes given here do not work. I have been struggling for several hours.
Please help.

How are you setting the $offset variable? Try something like this, code is not tested but it will give you idea to get comments pagination working.
<?php
$current_page = get_query_var( 'cpage' ) ? get_query_var( 'cpage' ) : 1;
$comments_per_page = 8;
$offset = ( $current_page - 1 ) * $comments_per_page;

Related

Pagination fails with CPT and dynamic tax_query

I have a search form. Choose a taxonomy, and select one or more terms. I want to paginate the results.
Here is the code:
<?php
if(isset($_POST['tax_type'])) {
$tax_type=$_POST['tax_type'];
$terms = $_POST[$tax_type];
$term_list = implode("','", $terms);
$term_list1 = implode(", ", $terms);
$term_list = "'".$term_list."'";
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$giftfinder_args = array(
'post_type' => 'products',
'posts_per_page'=>"1",
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => $tax_type,
'field' => 'slug',
'terms' => explode(',',$term_list),
),
),
);
echo '<div class="results"><span class="eyebrow">search results</span>';
echo '<div class="cat_label">“' . $term_list1 . '”</div></div>';
// the query
$giftfinder_query = new WP_Query( $giftfinder_args );
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $giftfinder_query;
?>
<?php if ( $giftfinder_query->have_posts() ) : ?>
<!-- the loop -->
<?php while ( $giftfinder_query->have_posts() ) : $giftfinder_query->the_post();
$thumb = get_the_post_thumbnail(null, 'medium');
?>
<div class="prod"><?php if(empty($thumb)) {echo '<div style="width:265px;height:265px;background:#eee;"></div>';} else {the_post_thumbnail('medium');} ?><span class="truncate"><?php the_title(); ?></span></div>
<?php endwhile; ?>
<div style="clear:both;"></div>
<!-- end of the loop -->
<?php
the_posts_pagination( array(
'prev_text' => __( 'Previous page', 'twentyfifteen' ),
'next_text' => __( 'Next page', 'twentyfifteen' ),
'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentyfifteen' ) . ' </span>',
) );
?>
<?php wp_reset_postdata(); ?>
<?php else : get_template_part( 'content', 'none' ); endif; ?>
<?php } ?>
First page is fine, but no results appear on paginated pages.
As you can see, I'm trying to use the pagination fix that turns my query into $wp_query:
// the query
$the_query = new WP_Query( $args );
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $the_query;
But like I said, no results beyond first page.
I was going to try pre_get_posts but I can't figure out how to code it since every query has unique arguments based on the user's choice of taxonomy and searched terms.
I also tried 'add_args' to the paginate_links() function but could not figure out how to format the resulting get string.
BTW, right now, the query just returns one post to make it easy to check pagination.
Any suggestions appreciated!
Not sure if this is the only issue, but it looks like you have a typo.
You are setting $page:
$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
But looking for $paged:
'paged' => $paged,

Display Random Product Link

I need PHP-code for WordPress (Woocommerce) to display random product link.
For example, I have Product1 and want to display on this page (in description of my product):
"See also other products: [Product2 - link] and [Product3 - link]"
Don't know how, I just need php code to insert it in post/pages/products and everywhere I want on my site.
I'm not a coder and I found this code, for example, to display page title with link, but it's not what I need
<?php
echo ''.get_the_title($product_id).'';
?>
But how to get random product, don't know, thanks for help.
Try this :
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand',
'post_type' => 'product' );
$random_products = get_posts( $args );
foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
<?php the_title(); ?>
<?php endforeach;
wp_reset_postdata();
The Perfect solution for outputting a single random product which can be achieved using the following code.
<?php
$post_array=array();
$args = array(
'post_type' => 'product',
'posts_per_page' => 12
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
array_push($post_array,get_the_ID());
endwhile;
$random_key = array_rand($post_array, 1);
echo ''.get_the_title($post_array[$random_key]).'';
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
Have tested the same for you. It worked. Lemme Know if the same worked for you too.

Make query_posts exclude post based on a term in the post title

Posts on my page are fetched via this query:
<?php
$limit = get_option('posts_per_page');
query_posts(array(
'showposts'=>62,
'more' => $more = 0,
'v_sortby' => 'views',
'v_orderby' => 'DESC',
'v_outtype' => 'content',
'v_timespan' => 'year',
'paged' => $paged
));?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
However, I want to exclude all posts which title contains the word "Metal".
I know there's a 'post__not_in' => feature, but I'm not sure how to implement it.
I tried
$exclude1 = get_page_by_title('Metal'); and then including
'post__not_in' => array($exclude1->ID,$exclude2->ID)
but that seems to center around pages, and not post titles itself.
In the arguments:
$args['special_search'] = 'Metal';
In your functions.php:
add_filter( 'posts_where', 'special_search_posts_where', 10, 2 );
function special_search_posts_where( $where, $query ) {
if (isset($query->query_vars["special_search"])) {
global $wpdb;
$where .= ' AND ' . $wpdb->posts . '.post_title NOT LIKE \'%' . $query->query_vars["special_search"] . '%\'';
}
return $where;
}

How to get number of results from query_posts?

I'm printing posts and I want to get number of results, how can I do that?
This is part of my code:
if (have_posts()) :
$args = array(
'showposts' => '5',
'paged' => $paged
);
$thePosts = query_posts($args);
...
Thank's for help
SOLVED:
if (have_posts()) :
$args = array(
'showposts' => '5',
'paged' => $paged
);
$thePosts = query_posts($args);
global $wp_query;
echo $wp_query->found_posts;
...
To display the number of results of a search, use:
Search Result for
<?php
/* Search Count */
$allsearch = &new WP_Query("s=$s&showposts=-1");
$key = wp_specialchars($s, 1);
$count = $allsearch->post_count; _e('');
_e('<span class="search-terms">');
echo $key; _e('</span>');
_e(' — ');
echo $count . ' ';
_e('articles');
wp_reset_query();
?>
This was taken from: WP Beginner.
The correct answer is
if (have_posts()) :
$args = array(
'showposts' => '5',
'paged' => $paged
);
$thePosts = query_posts($args);
echo $thePosts ->found_posts;
...
This will give you the results: Showing results 11-20 of 46, for instance.
$args = array(
'cat'=> $cat,
'posts_per_page' => 10,
'paged' => $paged,
's'=> $s
);
query_posts($args);
$startpost=1;
$startpost=10*($paged - 1)+1;
$endpost = (10*$paged < $wp_query->found_posts ? 10*$paged : $wp_query->found_posts);
?>
<h2 class="displayResult">Showing results <?php echo $startpost; ?> - <?php echo $endpost; ?> of <?php echo $wp_query->found_posts; ?></h2>
If this is not a search page, simply remove the line "'s'=> $s".
If you do need it, make sure you declare the variable as $_GET['s'] above.
Easy. To display number of results for this current page, use
// Showing Page X of Y
print filter_var( absint( $GLOBALS['wp_query']->post_count ), FILTER_SANITIZE_NUMBER_INT );
For the total amount of results, use
print filter_var( absint( $GLOBALS['wp_query']->found_posts ), FILTER_SANITIZE_NUMBER_INT );
display numbers of search results :
<?php global $wp_query;
echo $wp_query->post_count; ?>
query_posts( $args );
global $wp_query;
print_r($wp_query->max_num_pages);
It help me.

Wordpress custom taxonomy pagination not working

I’m using the WP PageNavi plugin for pagination. This particular problem in not getting the taxonomy-portflio-category.php page to paginate is also a problem when WP PageNavi is turned off.
I’ve had a heck of a time getting pagination to work on the homepage and on a page template page, but I did get them to work. Here’s their code:
page-home.php (used as a Page template on a static front page called “Home”)
$paged = 1;
if ( get_query_var('paged') ) $paged = get_query_var('paged');
if ( get_query_var('page') ) $paged = get_query_var('page');
$i = 0;
$loop = new WP_Query( array( 'post_type' => 'portfolio', 'paged' => $paged, 'posts_per_page' => 24 ) );
while ( $loop->have_posts() ) : $loop->the_post();
// output
$i++; endwhile;
if ( function_exists( 'wp_pagenavi' ) ) {
wp_pagenavi( array( 'query' => $loop ) );
wp_reset_postdata();
}
Pagination works!
page-portfolio.php (used as a Page template on a Page called “Work”)
$i = 0;
$loop = new WP_Query( array( 'post_type' => 'portfolio', 'paged' => get_query_var( 'paged' ), 'posts_per_page' => 24 ) );
while ( $loop->have_posts() ) : $loop->the_post();
// output
$i++; endwhile;
if ( function_exists( 'wp_pagenavi' ) ) {
wp_pagenavi( array( 'query' => $loop ) );
wp_reset_postdata();
}
Pagination works!
taxonomy-portfolio-category.php (used as a way to display portfolio sections e.g. print, photography, etc.)
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
global $wp_query;
query_posts( array_merge( $wp_query->query, array( 'posts_per_page' => 2 ) ) );
if (have_posts()) : while ( have_posts() ) : the_post();
// output
endwhile; endif;
if ( function_exists( 'wp_pagenavi' ) ) {
wp_pagenavi();
}
Page 1 (/portfolio/interactive/) looks great! It’s definitely only posting 2 items and it calculates the correct number of pagination pages. But when you click on page 2 or 3 or 4 (/portfolio/interactive/page/2/) the site defaults to index.php and shows “Page not found”. Pagination fails!
Hopefully I can resolve this soon. I’ve seen A LOT of people with this same problem of pagination on custom taxonomy pages, but no solid solutions. Please help!
You Need to set posts per page to 24 on the Settings -> Reading page in WP admin. Hope this helps someone.
I have tried using WP-Pagenavi but it never worked so i used the pagination from Wordpress it self, i used the twentyfourteen_paging_nav() function form Twentyfourteen becuse it has a taxonomy page, here is the code:
if ( ! function_exists( 'twentyfourteen_paging_nav' ) ) :
function twentyfourteen_paging_nav() {
global $wp_query, $wp_rewrite;
// Don't print empty markup if there's only one page.
if ( $wp_query->max_num_pages < 2 ) {
return;
}
$paged = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1;
$pagenum_link = html_entity_decode( get_pagenum_link() );
$query_args = array();
$url_parts = explode( '?', $pagenum_link );
if ( isset( $url_parts[1] ) ) {
wp_parse_str( $url_parts[1], $query_args );
}
$pagenum_link = remove_query_arg( array_keys( $query_args ), $pagenum_link );
$pagenum_link = trailingslashit( $pagenum_link ) . '%_%';
$format = $wp_rewrite->using_index_permalinks() && ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : '';
$format .= $wp_rewrite->using_permalinks() ? user_trailingslashit( $wp_rewrite->pagination_base . '/%#%', 'paged' ) : '?paged=%#%';
// Set up paginated links.
$links = paginate_links( array(
'base' => $pagenum_link,
'format' => $format,
'total' => $wp_query->max_num_pages,
'current' => $paged,
'mid_size' => 1,
'add_args' => array_map( 'urlencode', $query_args ),
'prev_text' => __( '← Previous', 'twentyfourteen' ),
'next_text' => __( 'Next →', 'twentyfourteen' ),
) );
if ( $links ) :
?>
<nav class="pagination-contaner" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Posts navigation', 'twentyfourteen' ); ?></h1>
<ul class="pagination">
<?php echo $links; ?>
</ul><!-- .pagination -->
</nav><!-- .navigation -->
<?php
endif;
}
endif;
I ran into similar issue, it took me hours of googling! I found the solution at last.
Add the following code to functions.php in your theme folder:
$option_posts_per_page = get_option( 'posts_per_page' );
add_action( 'init', 'my_modify_posts_per_page', 0);
function my_modify_posts_per_page() {
add_filter( 'option_posts_per_page', 'my_option_posts_per_page' );
}
function my_option_posts_per_page( $value ) {
global $option_posts_per_page;
if ( is_tax( 'portfolio-category') ) {
return 2;
} else {
return $option_posts_per_page;
}
}
URL for the solution
May be you need to enable search to enable pagination
While declaring custom taxonomy you should disable search excluding.
exclude_from_search => false
This fixed my problem.
I would like to share following solution (add this code to functions.php in your theme):
function fix_taxonomy_pagination ( $query ) {
// not an admin page and it is the main query
if (!is_admin() && $query->is_main_query()){
if(is_tax()){
// where 24 is number of posts per page on custom taxonomy pages
$query->set('posts_per_page', 24);
}
}
}
add_action( 'pre_get_posts', 'fix_taxonomy_pagination' );
source

Resources