0

Please help with pagination

I have code that works fine (functions.php)

function projects_custom_number_of_posts( $query ) {
    $query->set( 'posts_per_page', 2 );
    return;
}
add_action( 'pre_get_posts', 'projects_custom_number_of_posts');

when I change to, pagination stops working

function projects_custom_number_of_posts( $query ) {
    $postsperpage = $query->get( 'posts_per_page' );
    $query->set( 'posts_per_page', $postsperpage );
    return;
}
add_action( 'pre_get_posts', 'projects_custom_number_of_posts');

It is necessary that the data is taken from the 'posts_per_page'

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array('product_cat' => $cat, 'post_type' => 'product',  'posts_per_page' => 2, 'paged' => $paged ); $query = new WP_Query( $args );

if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
4
  • I don't understand what you're trying to do, your 2nd block of code is just setting the posts_per_page to the current posts_per_page? You're also doing it for every query that gets run. Oct 29, 2017 at 1:29
  • It is necessary for the pagination to work in loop product
    – Vova
    Oct 29, 2017 at 18:04
  • Your pre_get_posts filter is pointless because you then replace the main query and use a secondary WP_Query in the template. Use pre_get_posts and only pre_get_posts and the problem will vanish. Your second code block is also a non-operation
    – Tom J Nowell
    Dec 29, 2020 at 13:42
  • Also note that WooCommerce is off topic here
    – Tom J Nowell
    Dec 29, 2020 at 13:42

1 Answer 1

0

Having same problem. Ended up with the following codes

global $woocommerce_loop;
$woocommerce_loop['paged'] = (isset($woocommerce_loop['paged'])) ? $woocommerce_loop['paged'] : 1;
$woocommerce_loop['total'] = $custom_query->found_posts;
$woocommerce_loop['post_count'] = $custom_query->post_count;
$woocommerce_loop['per_page'] = $per_page;
$woocommerce_loop['total_pages'] = ceil($custom_query->found_posts/$per_page);
$woocommerce_loop['current_page'] = $args['paged'];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.