Home > Mobile >  wordpress pagination page/3 using index template instead of taxonomy-product-cat
wordpress pagination page/3 using index template instead of taxonomy-product-cat

Time:08-09

I have added pagination to woocommerce custom product everything works fine till page 2 as soon as I click on page 3 nothing shows up and also it is somehow using the index template on page 3. I am not sure where I am doing it wrong.

and also I tried changing posts per page to 6 in WordPress reading setting.

<?php    
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$category_id = "clothing"; 
$args = array(
    'post_type'        => 'product',
    'posts_per_page'   => 6, 
    'post_status'      => 'publish',
    'suppress_filters' => false,
    'paged' => $paged,
    'tax_query'        => array(
        array(
            'taxonomy' => 'product_cat',
            'terms'    => $category_id,
            'field'           => 'slug'
        ),
    ),
    
);

$products_query = new WP_Query($args);
echo $total_pages = $products_query->max_num_pages;
// echo "<pre>"; print_r($products_query);
if($products_query->have_posts()){
    foreach($products_query->posts as $product_id){
       echo $product = wc_get_product($product_id);
       echo  $product_title = get_the_title($product_id);
       echo  $product_image = get_the_post_thumbnail($product_id);
      echo  $product_price = $product->get_price();
       echo  $product_link = get_the_permalink($product_id);
    }
} 

if ($total_pages > 1) :{

        $current_page = max(1, get_query_var('paged'));

        echo paginate_links(array(
            'base' => get_pagenum_link(1) . '%_%',
            'format' => '/page/%#%',
            'current' => $current_page,
            'total' => $total_pages,
            'prev_text'    => __('« prev'),
            'next_text'    => __('next »'),
        ));
    }    
endif;
wp_reset_postdata(); ?>

CodePudding user response:

You should use pre_get_posts hook on the functions.php file. Because it's too late to change the paginated query with new WP_Query after the template included. Including the taxonomy-product-cat is determined by the general posts_per_page value on the Reading Settings.

add_action( 'pre_get_posts', function ($query) {
    if ( is_admin() || !$query->is_main_query() ) return;
    if ( $query->is_tax( 'product_cat' ) ) {
        $query->set('posts_per_page', 6 );
    }
});
  • Related