0

I have a custom taxonomy query setup that shows posts from the same post type and share the same taxonomy term. The markup looks as follows:

        <?php  
        $terms = wp_get_post_terms( $post->ID, 'products-category' );
        if($terms){
          // post has course_type terms attached
          $course_terms = array();
          foreach ($terms as $term){
           $course_terms[] = $term->slug;
          }

         $original_query = $wp_query;
         $wp_query = null;
         $wp_query = new WP_Query( array(
         'post_type' => 'regularproducts',
         'tax_query' => array(
          array(
         'taxonomy' => 'products-category',
         'field' => 'slug',
         'terms' => $course_terms, //the taxonomy terms I'd like to dynamically query
         'posts_per_page' => '4'
            ),
          ),
          'orderby' => 'title',
          'order' => 'ASC'
          ) );

        if ( have_posts() ): ?>
...etc

But despite me using 'posts_per_page' => '4' it is still showing all the posts that are related and not just 4. I can't figure out why, any suggestions would be greatly appreciated!

1

This is why code indentation is so important! Your posts_per_page argument is actually part of your tax_query:

'post_type' => 'regularproducts',
'tax_query' => array(
    array(
        'taxonomy' => 'products-category',
        'field' => 'slug',
        'terms' => $course_terms, //the taxonomy terms I'd like to dynamically query
        'posts_per_page' => '4'
    ),
),
'orderby' => 'title',

Instead, you should have:

$wp_query = new WP_Query(
    array(
        'posts_per_page' => '4',
        'post_type' => 'regularproducts',
        'tax_query' => array(
            array(
                'taxonomy' => 'products-category',
                'field' => 'slug',
                'terms' => $course_terms, //the taxonomy terms I'd like to dynamically query
            ),
        ),
        'orderby' => 'title',
        'order' => 'ASC',
    )
);

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.