skip to Main Content

Well I’m trying to get WooCommerce product using WP_Query, with some of params

It gives me results but sort by product title is not working, also when I try adding a category in params it doesn’t work.

here is what im trying:

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

$params = array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => 20,
//    'category__in' => array(22),
    'paged' => $paged,
    'orderby' => 'title',
    'order' => 'ASC'
);

$query = new WP_Query( $params );


$total_found_posts = $query->found_posts;
$total_page = ceil($total_found_posts / 20);

Any help appreciate

thanks

2

Answers


  1. Chosen as BEST ANSWER

    Well, My query was working correctly, problem was my "Post Types Order" plugin which was adding extra condition to orderby clause.

    i changed my params to this:

    $params = array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => 20,
    'ignore_custom_sort' => true,
    'paged' => $paged,
    'orderby' => 'title',
    'order' => 'ASC'
    

    );

    and it worked as i wanted.


  2. Your query worked for me. Perhaps the issue is with how you extract the products and display them?

    I implemented the following on one of my sites, and it listed the first 20 products in alphabetical order:

    add_action('astra_header_before', 'entreprenerds_callback');
    function entreprenerds_callback() {
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $params = array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'posts_per_page' => 20,
            // 'category__in' => array(22),
            'paged' => $paged,
            'orderby' => 'title',
            'order' => 'ASC'
        );
        $query = new WP_Query( $params );
        $total_found_posts = $query->found_posts;
        $total_page = ceil($total_found_posts / 20);
    
        echo "## " . $total_found_posts . " ##"; // shows me 51
    
        while($query->have_posts()) {
            $query->the_post();
            echo get_the_title() . '<br />';
        }
    }
    

    Are you using the correct query object in your loop?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search