I am trying to use a custom WP_Query for my loop in order to limit the number of posts that I show per page. However, the pagination functions doesn't seem to respect this limit that I set. Here is my code:
$current_page = (get_query_var('paged')) ? get_query_var('paged') : 1;
$author_post_args = array(
'post_type' => 'post',
'author_name' => $curauth->user_nicename,
'posts_per_page' => 5,
'paged' => $current_page,
'orderby' => 'modified',
'no_found_rows' => true,
'ignore_sticky_posts' => '1'
);
$loop = new WP_Query( $author_post_args );
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $loop;
if($loop->have_posts()):
while($loop->have_posts()): $loop->the_post(); ?>
<div class="post-list">
<?php
$title = the_title("", "", false);
?>
<h2><?php echo $title; ?></h2>
<time>Last Updated — <?php the_modified_date('F j, Y'); ?></time>
<p><?php the_excerpt(); ?></p>
</div>
<?php
endwhile;
endif;
wp_reset_postdata();
previous_posts_link('<i class="fas fa-backward"></i> Newer Posts');
next_posts_link('Older Posts <i class="fas fa-forward"></i>', $loop->max_num_pages);
$wp_query = NULL;
$wp_query = $temp_query;
I searched for a solution on the website and found this question. The solution seems to work for the OP but not for me.
In my case, the posts per page are limited to 5. However, the number of pages is still stuck at 3. I can't go to page 4 and get a Not Found error. There are total 26 posts by the author. Therefore, I should be able to go to page 6.
The number of pages is still determined by the functions based on the value specified under Settings > Reading > Blog pages show at most in WordPress dashboard which is set to 10.
What am I doing wrong?
Thanks.
The problem is that WordPress is working off of the assumption that you're still expecting 10 posts per page because your query is effectively a standalone query in the middle of a page. Are you just trying to limit the number of posts per page on this particular post type? Or is there something else you're trying to do?
You can achieve this in a far cleaner way by using pre_get_posts
function tweak_posts_per_page( $query ) {
if( !is_admin() && $query->is_author() && $query->is_main_query() ) :
$query->set( 'posts_per_page', 5 );
$query->set( 'orderby', 'modified' );
return;
endif;
}
add_action('pre_get_posts', 'tweak_posts_per_page');
Add this code in your functions.php file or similar; if needed you can add additional conditionals to the IF statement to handle when this adjustment will be applied. You should find your pagination will work after that.
pre_get_posts is used to adjust the query that WordPress will run before it runs the query
Additionally, you can remove the query from your code altogether - just keep the loop in there to loop through what is now your adjusted main query.
edit: added the additional 'is_author' conditional statement, and added the 'orderby' adjustment
Related
I made a "load more" button to my website, following this awesome tutorial.
Everything works fine, but in the homepage i have 3 different loops (1 sticky post, 3 evidence) and the load more starts from post #5.
In the main loops, I have excluded the already-showed posts with the IDs and "post__not_in" and everything works fine.
The problem is when I call the load more, the loop starts from post 1. If I set to start from page 2 I have a duplicate post (that's because I have to load post in multiple of 3).
I'have tried to get the IDs list in my loadmore file with GLOBALS, but it seems not working :(
How can I pass my main loop variable to the load more query?
This is my main loop:
<?php
$myquery = new WP_Query([
'post_type' => 'post',
'posts_per_page' => 3,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'post__not_in' => $ids
]); if($myquery->have_posts()): ?>
<div class="articles-container append-posts">
<?php
while($myquery->have_posts()) : $myquery->the_post();
$ids[] = get_the_ID(); ?>
<?php get_template_part( 'template-parts/loop', 'posts' ); ?>
<?php endwhile; ?>
</div>
This is the load-more file:
function misha_loadmore_ajax_handler(){
// prepare our arguments for the query
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
$args['post_type'] = 'post';
$args['post_per_page'] = 3;
$args['orderby'] = 'date';
$args['order'] = 'DESC';
// it is always better to use WP_Query but not here
query_posts( $args );
if( have_posts() ) :
// run the loop
while( have_posts() ): the_post();
// look into your theme code how the posts are inserted, but you can use your own HTML of course
// do you remember? - my example is adapted for Twenty Seventeen theme
get_template_part( 'template-parts/loop', 'posts' );
// for the test purposes comment the line above and uncomment the below one
// the_title();
endwhile;
endif;
die; // here we exit the script and even no wp_reset_query() required! }
I am having trouble with Wordpress pagination. I have a custom archive page displaying custom post types from the specific category. I want to use pagination and display 12 posts per page. My problem is that pagination works correctly but only up to the 8th page. After that I am being presented with "Page not found".
I am using theme built-in function to display page navigation (1, 2... 10, 11). It correctly shows 11 pages in total, but they seem not to work after the 8th page.
$taxonomy = 'product_cat';
$term_id = get_queried_object()->term_id;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'product',
'paged' => $paged,
'posts_per_page' => '12',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $term_id
)
)
);
<?php $wp_query = new WP_query( $args ); ?>
<?php if( $wp_query->have_posts() ): ?>
<?php while( $wp_query->have_posts() ): ?>
<?php $wp_query->the_post(); ?>
//post content
<?php endwhile; ?>
<?php endif; ?>
<?php s7upf_paging_nav();?>
<?php wp_reset_postdata(); ?>
#edit
When I go to a different category page which should have 12 pages they work correctly up to the 9th page.
If I go to the one that has 2 pages, only the first one works.
I tried updaing permalinks. Setting posts per page to 12 in wordpress settings.
When i change posts per page in my query args to -1 it correctly shows all the posts on one page.
When manually setting the number of a page to display ('paged' => '11') it also displays correct page with correct posts.
You are using the wrong query. On page you are creating your own query instead of the actual query the page already did.
This will also be better for performance.
Step 1. Check what is in the normal query.
At the top of taxonomy-product_cat.php
global $wp_query;
var_dump( $wp_query->query_vars );
That probably fits mostly.
Step 2. Do the normal loop
Remove all your query stuff (maybe keep a backup of the $args for the next step)
example: Replace
<?php if( $wp_query->have_posts() ): ?>
with
<?php if( have_posts() ): ?>
And so on.
Step 3. Edit the main query
We are going to use the hook pre_get_posts
add_action('pre_get_posts', 'so_53315648');
function so_53315648( WP_Query $wp_query ){
// only check this on the main query
if (! $wp_query->is_main_query() ){
return;
}
// only check this on the product_cat taxonomy
if ( ! $wp_query->is_tax('product_cat')) {
return;
}
// maybe do some more checks?
$wp_query->query_vars['posts_per_page'] = 12;
// Is this really needed??
//$wp_query->query_vars['posts_type'] = 'product';
// tweak the query the way you like.
}
As you can see $wp_query->query_vars should pretty much be the same $args. But do not overwrite it. This might break other stuff.
Of course I could not test your specific site. But the answer should be inside the pre_get_posts hook. And tweaking the main query instead of doing a extra separate one.
Test, also check the var_dump of step 1 that your changes are coming through.
The checks at the top are to stop other pages from being affected, maybe you need more?
Let me know.
I have a custom Wordpress widget which allows the user to filter products via attributes (custom taxonomies).
It all happens via an Ajax call, but I'm having trouble keeping the pagination up to date based on the filtered results.
For example:
If the page loads 30 products, 10 to a page = 3 pages of results.
The user then filters by an attribute which reduces that 30 products to 20. I need the pagination to change to just 2 pages of results.
Here's a sample of the WP_Query that replaces the default page content. You can see the woocommerce_pagination() which doesn't appear to work in this environment.
// Args
$args = array(
'post_type' => 'product',
'posts_per_page' => 10,
'orderby' => 'name',
'order' => 'ASC',
'tax_query' => $tax_query
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
woocommerce_product_loop_start();
while( $query->have_posts() ): $query->the_post();
wc_get_template_part( 'content', 'product' );
endwhile;
woocommerce_product_loop_end();
// TODO - get pagination working
woocommerce_pagination();
wp_reset_postdata();
else :
echo '<p>No products found</p>';
endif;
WooCommerce pagination works based on global $wp_query variable. But you are using your own $query variable. That's why it is obvious why it is not working.
You have 2 ways to go:
First is using query_posts instead of WP_QUERY class.
The second way is a small hack, where you can cheat $wp_query pagination argument.
Here it is:
global $wp_query;
$wp_query->max_num_pages=$query->max_num_pages;
// TODO - get pagination working
woocommerce_pagination();
I'm using the following wp_query on a few pages in Wordpress, and as you can see I am trying to ensure the query is paginated. Everything is working successfully on a custom page template page-articles.php, however I'm unable to get the same results on the archive.php template.
The pagination link renders successfully (e.g mydomain.com/category/my-cat/page/2) however upon clicking the link does not work, it just throws a 404 error? How can these links not go anywhere?
I'm assuming there is some issue with using custom wp_query on the archive.php template?
Thanks!
Query
$args = array(
'post_type' => 'post',
'posts_per_page' => 1,
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC'
);
$articles = new WP_Query($args );
?>
Loop
<?php if ( $articles->have_posts() ) : ?>
<?php while ( $articles->have_posts() ) : $articles->the_post(); ?>
Posts here!
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
Pagination
<nav>
<div class="prev"><?php echo get_previous_posts_link( 'Previous', $articles->max_num_pages ); ?></div>
<div class="next"><?php echo get_next_posts_link( 'Next', $articles->max_num_pages ); ?></div>
</nav>
After a bit of digging around, and with help from this article, the below solution solves the issue. Just place this in your functions.php file and thats it. The below implementation works for archives of custom post types, as well as categories.
/**
* Wordpress has a known bug with the posts_per_page value and overriding it using
* query_posts. The result is that although the number of allowed posts_per_page
* is abided by on the first page, subsequent pages give a 404 error and act as if
* there are no more custom post type posts to show and thus gives a 404 error.
*
* This fix is a nicer alternative to setting the blog pages show at most value in the
* WP Admin reading options screen to a low value like 1.
*
*/
function custom_posts_per_page( $query ) {
if ( $query->is_archive('cpt_name') || $query->is_category() ) {
set_query_var('posts_per_page', 1);
}
}
add_action( 'pre_get_posts', 'custom_posts_per_page' );
Yes, it is.
It is because main query of archive.php is kept unchanged while you are playing with WP_QUERY. Try use query_posts() in archive.php.
query_posts($args);
and then default loop (instead of $articles)
<?php if ( have_posts() ) : ?>
<?php while (have_posts() ) : the_post(); ?>
Posts here!
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
I'm hoping someone can help me figure this one. It's been giving me problems for a bit. I'm attempting to have a custom category page display the most recent post at the beginning of the page, and below in a separate loop I wish to display the rest of the posts in the given category WITH pagination, offsetting the loop by 1. I've searched numerous ways to do this and can't quite come up with a solution! Any help you can give for this one I'd be soooo grateful for! Thank you in advance! Here's my code:
<?php query_posts( 'cat=3&showposts=1&offset=0'); ?>
<?php while (have_posts()) : the_post(); ?>
<div class="firstPost">
Snipped post style
</div>
<div class="prevHeader">Previous Episodes</div>
<?php endwhile; ?>
<div class="container archiveContainer">
<?php
// set the "paged" parameter (use 'page' if the query is on a static front page)
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
// the query
$the_query = new WP_Query( 'cat=3&posts_per_page=6&offset=1&paged=' . $paged );
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php
// the loop
while ( $the_query->have_posts() ) : $the_query->the_post();
?>
<div class="prevEntries">
Snipped Post Style
</div>
<?php endwhile; ?>
</div>
<div style="width:100%">
<span style="display:inline-block; margin-left:10px; float:left" class="nav-previous"><?php next_posts_link( '<h4>Older posts</h4>', $the_query->max_num_pages ); ?></span>
<span style="display:inline-block; margin-left:10px; float:right" class="nav-next alignright"><?php previous_posts_link( '<h4>Newer posts</h4>' ); ?></span></div>
<?php
// clean up after the query and pagination
wp_reset_postdata();
?>
<?php endif; ?>
This can certainly be done, but surely not with query_posts. It a case like this, it will outright fail. Also, offsets breaks pagination and are quite difficult to work with if you don't know what you are doing
I don't have time to code now, but here is an idea:
If you need to display the latest post on all your pages, then you can do the following.
Remove you custom query and your offset so that everything works normal. Make use of the default loop and paginate as normal
To display your first post on every page, create a custom query with WP_Query and place it where you need to display this post .See the link on how to properly construct that query. Please do not use query_posts
You will now see that you have the first post displayed twice. To counter this, wrap your custom query in a is_paged() condition.
EDIT
You can try something like this. (PS! showposts is depreciated, use posts_per_page. Also, you can removed the paged parameter when setting an offset as it will be ignored)
(CAVEAT Untested)
if( is_paged() ) {
$args = array(
'posts_per_page' => 1,
'cat' => 3,
);
$q = new WP_Query( $args );
if( $q->have_posts() ) {
while( $q->have_posts() ) {
$q->the_post();
// Display your loop elements
} //end while
wp_reset_postdata();
} // end if have_posts()
} //end if is_paged
// Now for your main loop
// set the "paged" parameter (use 'page' if the query is on a static front page)
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$the_query = new WP_Query( 'cat=3&posts_per_page=6&paged=' . $paged );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
// Your loop elements
}
wp_reset_postdata();
}
Codex states : Specifying hard-coded offsets in queries can and will break pagination since offset is used by WordPress internally to calculate and handle pagination.
See the following link. As described on the page you'll need to use a hook and filter.