How can I get all taxonomy entries in WordPress Query?

I have a simple Content Types plugin and a created Post type in WP call Recipes. I also added a taxonomy category and created 4 categories such as Starter, Drinks, etc. Etc.

Now in the WP request I need to get all the starter entries. So how can I get this?

I use this query, but it does not work. It gives all the records type recipes Recipes Here is the query

$recipes = query_posts('post_type=recipes&taxonomy=recipescategory&category_name=Starters'); 
+5
source share
3 answers

You have a lot of errors in the code and a misunderstanding regarding the categories.

  • Never use query_posts to create a custom query

Note. This feature is not intended for use by plugins or themes. As explained below, there are more efficient, more effective options for modifying the main request. query_posts () is too simplistic and problematic way to modify the main page request by replacing it with a new instance of the request. It is inefficient (re-runs SQL queries) and in some cases it will fail unexpectedly (especially often when working with pagination)

  • If you need to run a custom query, use WP_Query or get_posts

  • category_name accepts a category slug , not a name . Parameter name is cheating

  • "Categories" related to user taxonomy are called terms. I wrote a post that I also included in the code, which you can check here , it describes the differences.

  • To get posts from a custom taxonomy, you need to use tax_query . Category options will not work here.

Based on the foregoing, create your request so that it looks like this:

 $args = array( 'post_type' => 'recipes', 'tax_query' => array( array( 'taxonomy' => 'recipescategory', 'field' => 'name', 'terms' => 'Starters', ), ), ); $query = new WP_Query( $args ); if( $query->have_posts() ){ while( $query->have_posts() ) { $query->the_post(); //Your loop elements } wp_reset_postdata(); } 
+5
source

try

  $ar = array ( 'post_type'=>'recipes', 'taxonomy'=>'recipescategory', 'category_name'=>'Starters' ); $posts = get_posts($ar); 

** foreach loop **

  foreach($posts as $p){ ?> <div class="sub_cont"> <div class="sub_img"> <?php $url = wp_get_attachment_url( get_post_thumbnail_id($p->ID));?> <a href="<?php echo $permalink = get_permalink( $p->ID); ?>"><img src="<?php echo $url; ?>" longdesc="URL_2" alt="Text_2" /> </a> </div> <div class="desc_title"> <a href="<?php echo $permalink = get_permalink( $p->ID); ?>"> <?php echo $post_title=$p->post_title; ?> </a> </div> <div class="cont_add"></div> </div> <?php } ?> 
+1
source

You can use the get_posts function

 $args = array("post_type"=>"recipes","category_name"=>"starter","posts_per_page"=>20); $starters = get_posts($args); 
0
source

Source: https://habr.com/ru/post/1205769/


All Articles