WP_Query sort category by term

I’m looking to make the code below sort my custom posttype (Product Type).
So that my active page will only show the posts with the term ‘Oil’, rather then ‘Fuel’ and ‘Tires’.

$args = array(
  'post_type' => 'Products',
  'posts_per_page' => -1
);

$my_query = new WP_Query( $args );

if ($my_query->have_posts()) {
  while($my_query->have_posts() ) {                           
    echo '<div class="custom-post">';
    $my_query->the_post();
    echo '<p>' . the_content() . '</p>';
    the_post_thumbnail();
    echo '</div>';
  }
  wp_reset_postdata();
}

// Edit, as a reply to the 3 below answers

Read More

I assume the foreach loop is a replacement for the WP_Query method, but the tax_query was new to me, and now that I know it exists I looked it up in the codex, however it still wont work. I honostly believe it is something as simple as me naming something in the tax_query wrongly, so I will show my taxonomy code here:

function my_custom_taxonomies() {
    register_taxonomy(
        'product-type',
        'products',
        array(
            'label' => 'Type of Product',
            'rewrite' => array( 'slug' => 'race-products' ),
            'hierarchical' => true,
        )
    );
}

add_action( 'init', 'my_custom_taxonomies' );

And the change to the $args:

$args = array(
    'post_type' => 'Products',
    'posts_per_page' => -1,
    'tax_query' => array( 
        array(
            'taxonomy' => 'product-type',
            'field' => 'slug',
            'terms' => 'oil'
        ),
    ),
);

Related posts

Leave a Reply

3 comments

  1. Try the below code:

    <?php
        $myposts = get_posts(array(
            'showposts' => -1,
            'post_type' => 'Products',
            'tax_query' => array(
                array(
                'taxonomy' => 'products_cat',
                'field' => 'slug',
                'terms' => 'oil'
                   );
            )
         )
        );
    
        foreach ($myposts as $mypost) {
              echo $mypost->post_title . '<br/>';
              echo $mypost->post_content . '<br/>';
              echo  get_the_post_thumbnail( $mypost->ID );
        }
    ?>
    
  2. $loop = new WP_Query(array(
        'posts_per_page' => 10,
        'post_type' => 'product_type',
        'order' => 'DESC',
        'orderby' => 'id',
        'post_status' => 'publish',
        'tax_query' => array(
            array(
                'taxonomy' => 'your_texonomy',
                'field' => 'slug',
                'terms' => 'Oil',
            ),
        ),));
    
  3. You need to try the following parameters in query.

    $args = array(
     'post_status' = 'publish',
     'tax_query' = array(
         'taxonomy' => 'categories',
         'field'    => 'id',
         'term'     =>  'category id here'
     )
    );
    $the_query = wp_query($args);