0

I would like to display a certain number of posts that belong to a specific custom category.

In my WordPress admin, we have Movies as general/global section under which we found:

  • Movies (List of all movies)
  • Add new movie
  • Movie Genre:

    • Movie genre 1
    • Movie genre 2
    • Movie genre 3

    • ...

For example, how would I display all movies that belong to Movie Genre 2?

The code below is for assistance, it displays all movies:

$rate_query = new WP_Query( array ( 
    'post_type' => 'movies', 
    'posts_per_page'=>'5' 
) ); 
while ( $rate_query->have_posts() ) : $rate_query->the_post();

1 Answer 1

0

The documentation for WP_Query is the place to look for this :)

In particular, you're after the taxonomy query parameters. Adding a tax_query to your code will look like this:

$rate_query = new WP_Query( array ( 
    'post_type' => 'movies', 
    'posts_per_page'=>'5',
    'tax_query' => array(
       array(
         'taxonomy' => 'movie_genre',
         'field' => 'slug',
         'terms' => array( 'movie-genre-2' ),
       ),
    ),
) ); 

Then just adjust the slugs of both your taxonomy and terms to match how they are defined. You can also include multiple terms.

In addition, there's a lot more fine-grained control you can add to the query if you like, which is covered in the aforementioned docs.

4
  • Thank you Tim for the quick reply, actually i followed your code but nothing happens! what i did is as follows: '$rate_query = new WP_Query( array ( 'post_type' => 'movies', 'posts_per_page'=>'5', 'tax_query' => array( array( 'taxonomy' => 'spanish-movies', 'field' => 'slug', 'terms' => array( 'movie-genre' ), ), ), ) ); '
    – Webjectif
    Jul 9, 2016 at 0:30
  • @Webjectif Just to clarify, have you also included the while loop in your original code?
    – Tim Malone
    Jul 9, 2016 at 1:32
  • yes i did and here is a preview of my code (txt.do/5iujm)
    – Webjectif
    Jul 9, 2016 at 13:32
  • @Webjectif That link doesn't work. Oh, I just noticed you might've got the taxonomy and term around the wrong way - movie-genre should be the taxonomy and spanish-movies the term :)
    – Tim Malone
    Jul 9, 2016 at 21:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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