- Функция query_posts в WordPress
- Использование функции «query_posts»
- how to query posts by category and tag?
- 5 Answers 5
- Edit: See below for proper way to query category and tag intersections.
- query_posts() │ WP 1.5.0
- Return
- Usage
- Examples
- #1 Exclude the posts from category 3, On the home page.
- #2 Get only the first part of the content $more = 0
- #3 Passing parameters in an array
- #4 Passing variables into query parameters
- #5 Change posts_per_page parameter for specific category
Функция query_posts в WordPress
У системы управления сайтом WordPress есть функции, которые сделаны для служебного пользования. То есть они сделаны только для системы. Но нет прямого запрета на их использование для программистов. К таким функция относится «query_posts«. Поговорим о ней.
Функция «query_posts» возвращает список записей, создаёт Цикл WordPress. По своему назначению эта функция — синоним «WP_Query«, который мы рассматривали в статье «Класс WP_Query в WordPress». Но она сделаны для служебных нужд WordPress и её использование может привести к сбоям в системе. Опишем их чуть подробнее.
WordPress формирует запрос к базе данных, основываясь на адрес URL страницы, настрочки ЧПУ (человеко понятный URL — типа транслитерации: «/eda/salat/cesar») и другие параметры. Таким образом система формирует особый запрос для выборки нужной записи или рубрики. Если же странице вызвать функцию «query_posts» вручную, то результаты её работы перезапишут результаты этого внутреннего запроса от системы. Из-за чего WordPress не сможет определить на какой странице находится, сколько записей выводить и т.п.
В отличии от класса «WP_Query» функция «query_posts» изменяет глобальную переменную «$wp_query«. Если Вам пришлось использовать функцию «query_posts» в своём коде, то обязательно после неё вызывайте «wp_reset_query«, чтобы установить значения глобальный переменных в начальное состояние.
Использование функции «query_posts»
Функция «query_posts» практически ничем не отличается в использовании от класса «WP_Query». То есть это функция, которая позволяет получить публикации из базы данных с самыми разными критериями. К примеру, можно получить публикации за определённое время, из определённых категории или с указанием значений произвольных полей. Единственная разница в том, что «query_posts» записывает результат прямо в глобальные переменные.
Рассмотрим запрос, сделанный с помощью этой функции:
'food' ] ); while(have_posts())< the_post(); echo '' . get_the_title() . '
'; echo get_the_content(); > wp_reset_query();
С помощью такого кода в глобальную переменную будут записаны публикации из базы данных, которые находятся в рубрике «food» (еда). Далее по коду мы использовали функции цикла WordPress, с помощью которых выводим заголовок и содержание каждой полученной публикации.
Функция «query_posts» должна находиться в коде до вызова Цикла WordPress, потому что она создаёт новый объект «$wp_query«, который будет использоваться в цикле. После неё WordPress не учитывает параметры, полученные в URL. Если хотите сохранить параметры оригинального запроса, то можете взять параметры текущего в глобальной переменной «$query_string«.
Как можно заметить, первым аргументом в функцию «query_posts» передаётся массив. Этот массив содержит параметры фильтра. Давайте попробуем вынести его в отдельную переменную и добавить условий:
'food', // фильтр по категории 'posts_per_page' => 5, // ограничение количества результатов на странице 'orderby' => 'comment_count' // сортировка по убыванию количества комментариев ); query_posts( $filter ); .
Принимает слудющие значения: ‘none’, ‘name’, ‘author’, ‘date’, ‘title’, ‘modified’, ‘menu_order’, ‘parent’, ‘ID’, ‘rand’, ‘relevance’, ‘comment_count’, ‘meta_value’, ‘meta_value_num’, ‘post__in’, ‘post_name__in’, ‘post_parent__in’
how to query posts by category and tag?
I am trying to show a list of posts that are related to category X and tag Y. I’ve tried the following code:
$args = array( 'posts_per_page' => 4, 'tag_id' => $tag_id, 'cat' => $cat_id, ); query_posts($args);
but it doesn’t work correctly and returns all the posts in the co\ategory. Would love to hear any insight you might have
I think with query_posts() you can only make use of category or tag. I’m not sure, but maybe the use of the function is limited to that which would mean that this is correctly working but it doesn’t do what you want to do it.
5 Answers 5
Edit: See below for proper way to query category and tag intersections.
global $wp_query; $args = array( 'category__and' => 'category', //must use category id for this field 'tag__in' => 'post_tag', //must use tag id for this field 'posts_per_page' => -1); //get all posts $posts = get_posts($args); foreach ($posts as $post) : //do stuff endforeach;
$args = array( 'tag' => get_queried_object()->slug, // If permalink like example.com/tag/example-tag, etc. 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'category', // Taxonomy, in my case I need default post categories 'field' => 'slug', 'terms' => 'interior', // Your category slug (I have a category 'interior') ), ) ); // Get all posts $posts_new = get_posts( $args );
I think this is bug in WordPress that has been commented on elsewhere, try using the name of the tag rather than the ID then it should work:
$args = array( 'posts_per_page' => 3, 'tag' => 'review', 'cat' => 9, ); query_posts($args);
Let us know how you get on, not sure what happens with tags with multiple words in the name.
I stumbled into this same issue and resolved it by making a MySQL request .
in short : get_post($args) will return you posts who have the category=MyCategory OR the tag=MyTag.
what you want is to change your OR to AND .
my logic was to go straight with a MySQL Query:
- Query 1 = Select all the posts who has the category MyCat
- Query 2 = Select all the posts who has the tag MyTag
- FinalLY : Select all the posts who are in Query 1 AND Query 2 .
I used wpdb instead of query_post();
A bit of code (returning published posts with category MyCat and tag MyTag ):
$query_byTag=" SELECT wp_posts.ID FROM wp_posts, wp_term_relationships, wp_terms WHERE wp_posts.ID = wp_term_relationships.object_id AND wp_terms.term_id = wp_term_relationships.term_taxonomy_id AND wp_terms.name = 'MyTag'"; $query_byCat=" SELECT wp_posts.ID FROM wp_posts, wp_term_relationships, wp_terms WHERE wp_posts.ID = wp_term_relationships.object_id AND wp_terms.term_id = wp_term_relationships.term_taxonomy_id AND wp_terms.name = 'MyCat'"; $query =" SELECT wp_posts.post_title AS title , wp_posts.post_content AS content, wp_posts.post_date AS blogdate FROM wp_posts WHERE wp_posts.post_status = 'publish' AND wp_posts.ID IN (".$query_byTag.") AND wp_posts.ID IN (".$query_byCat.") ORDER BY wp_posts.post_date DESC "; $result= $wpdb->get_results($query);
This is a dirty way to do it but I hope it helps =)
query_posts() │ WP 1.5.0
Sets up The Loop with query parameters. Note: This function will completely override the main query and isn’t intended for use by plugins or themes. Its overly-simplistic approach to modifying the main query can be problematic and should be avoided wherever possible. In most cases, there are better, more performant options for modifying the main query such as via the pre_get_posts action within WP_Query. This must not be used within the WordPress Loop.
Return
Usage
Examples
#1 Exclude the posts from category 3, On the home page.
To exclude posts that are in category 3 on the home page of your blog, you need to insert the following code in the front-page.php or home.php template files before you start the WordPress Loop: Override the main query with all posts in a specific category:
#2 Get only the first part of the content $more = 0
If you want to use the «read more» function with a new query, you must switch the global variable $more to 0 :
#3 Passing parameters in an array
query_posts( [ 'cat' => 22, 'year' => $current_year, 'monthnum' => $current_month, 'order' => 'ASC', ] );
As you can see, you can put each variable on a separate line here, and this is clearer and more readable.
#4 Passing variables into query parameters
You can create dynamic query parameters, if you want the query to change depending on the circumstances, write the value of the parameter to a variable and then pass the variable to the query parameters, you can do this in several ways:
1) Assembling a query using single quotes ‘ ‘ :
2) Assembling a query using double quotes «»
3) Using the global variable $query_string
Which contains the basic query for the query_posts() function. If we want to keep the standard output of WordPress posts (e.g. on a category page) but remove pagination (display all posts on one page), we can add the posts_per_page=-1 parameter to the basic query_posts function:
wp_reset_query(); // reset global $wp_query ?>
We can measure the value of posts_per_page by the specific (int) posts we need on one page. For example, posts_per_page=10 will display only 10 posts, but if you put a template tag posts_nav_link() at the end of the loop, a link to go to the next 10 posts (pagination link) will appear below the loop.
4) Adding parameters to the query
Saving the basic query of the current page and adding your own parameters to it. the query_posts() function completely rewrites the query, if for example we write query_posts (‘cat=1’) , other query parameters that are used for the current page (like sorting, pagination, etc.) will be lost and category 1 posts will be displayed with the other DEFAULT parameters. To keep the basic query parameters and supplement/replace them with your own, use the PHP function array_merge() (merges 2 arrays into one):
global $wp_query; query_posts( array_merge( ['cat' => 1 ], // this is the parameter we added $wp_query->query // this is an array of basic query of the current page ) );
This example is essentially the same as the one using the global variable $query_string , only as an array.
#5 Change posts_per_page parameter for specific category
The “Blog pages show at most” parameter in Settings > Reading can influence your results. To overcome this, add the posts_per_page parameter. For example:
// if this request is for 'category-slug' category change number of posts if ( is_category( 'category-slug' ) ) < query_posts( [ 'posts_per_page' =>999 ] ); >