WordPress сортировка query posts

Функция query_posts в WordPress

У системы управления сайтом WordPress есть функции, которые сделаны для служебного пользования. То есть они сделаны только для системы. Но нет прямого запрета на их использование для программистов. К таким функция относится «query_posts«. Поговорим о ней.

Функция «query_posts» возвращает список записей, создаёт Цикл WordPress. По своему назначению эта функция — синоним «WP_Query«, который мы рассматривали в статье «Класс WP_Query в WordPress». Но она сделаны для служебных нужд WordPress и её использование может привести к сбоям в системе. Опишем их чуть подробнее.

WordPress формирует запрос к базе данных, основываясь на адрес URL страницы, настрочки ЧПУ (человеко понятный URL — типа транслитерации: «/eda/salat/cesar») и другие параметры. Таким образом система формирует особый запрос для выборки нужной записи или рубрики. Если же странице вызвать функцию «query_posts» вручную, то результаты её работы перезапишут результаты этого внутреннего запроса от системы. Из-за чего WordPress не сможет определить на какой странице находится, сколько записей выводить и т.п.

Использование функции «query_posts»

Функция «query_posts» практически ничем не отличается в использовании от класса «WP_Query». То есть это функция, которая позволяет получить публикации из базы данных с самыми разными критериями. К примеру, можно получить публикации за определённое время, из определённых категории или с указанием значений произвольных полей. Единственная разница в том, что «query_posts» записывает результат прямо в глобальные переменные.

Рассмотрим запрос, сделанный с помощью этой функции: С помощью такого кода в глобальную переменную будут записаны публикации из базы данных, которые находятся в рубрике «food» (еда). Далее по коду мы использовали функции цикла WordPress, с помощью которых выводим заголовок и содержание каждой полученной публикации.

Как можно заметить, первым аргументом в функцию «query_posts» передаётся массив. Этот массив содержит параметры фильтра. Давайте попробуем вынести его в отдельную переменную и добавить условий: Перечислим возможные ключи фильтрации выборки и описания к ним:

Ключ Тип Описание
attachment_id число ID вложения. Используется если в «post_type» указано значение «attachment» .
author число/строка ID автора публикаций или разделённые запятыми ID авторов.
author_name строка Имя автора.
author__in массив Массив из ID авторов (логика «ИЛИ»).
author__not_in массив Массив из ID авторов, от которых не выводить публикации (логика «НЕ»).
cache_results true/false Кешировать ли полученную информацию публикации. По умолчанию: true
cat число/строка ID категории или строка из ID, разделённых запятыми (логика «ИЛИ»)
category__and массив Массив из ID категорий, в которых должна быть публикация (логика «И»)
category__in массив Массив из ID категорий, в которых может быть публикация (логика «ИЛИ»)
category__not_in массив Массив из ID категорий, в которых не должно быть публикации (логика «НЕ»)
category_name строка Ярлык категории (не тег)
comment_count массив/число Фильтрует результат по количеству комментариев. Если указано число, то покажет записи именно с таким количеством комментариев. Можно указать массив с ключами ‘value’ и ‘compare’, чтобы получилось так:

array(‘value’ => 5, ‘compare’ => ‘ ‘, ‘>=’, ‘ parent’ — возвращает массив из ID родительских записей
По умолчанию: » hour число Час (значение от 0 до 23). По умолчанию: » ignore_sticky_posts true/false Не включать в выборку прикреплённые публикации. Если указано «false», то исключает прикреплённые публикации из «post__in». По умолчанию: false m число Комбинация из года и месяца (4 цифры года и 2 цифры месяца). К примеру, «202010». По умолчанию: » meta_compare строка Оператор для сравнения со значением ‘meta_value’. meta_compare_key строка Оператор для сравнения со значением ‘meta_key’. meta_key строка Ключ (название) произвольного поля. meta_query массив Ассоциативный массив из аргументов WP_Meta_Query. meta_value строка Значение произвольного поля. meta_value_num число Цифровое значение произвольного поля. meta_type_key строка Тип значения поля ‘meta_key’. Смотрите подробнее «WP_Meta_Query» menu_order число Порядковый номер в списке меню. monthnum число Месяца публикации (от 1 до 12). По умолчанию: » name строка Ярлык публикации. nopaging true/false Отключить постраничную навигацию, выводить все публикации без разбиения на страницы. По умолчанию: false no_found_rows true/false Не считать количество полученных записей. Включение улучшает производительность. По умолчанию: false offset число Количество публикаций, которые надо пропустить с начала выборки. order строка Направление сортировки выборки. Возвращает ‘ASC’ или ‘DESC’. По умолчанию: ‘DESC’ orderby строка/массив Сортируем полученные публикации по параметру. Можно передать несколько опций массивом. Если нужно использовать сортировку по «meta_value» или «meta_value_num», то «meta_key=keyname» должно быть задано.

Принимает слудющие значения: ‘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’

Источник

Developer Resources

Sets up The Loop with query parameters.

Contents

Description

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.

Parameters

Return

WP_Post[]|int[] Array of post objects or post IDs.

More Information

Credit: Andrey Savchenko (rarst.net) / CC-By-SA.

query_posts() is a way to alter the main query that WordPress uses to display posts. It does this by putting the main query to one side, and replacing it with a new query. To clean up after a call to query_posts, make a call to wp_reset_query() , and the original main query will be restored.

It should be noted that using this to replace the main query on a page can increase page loading times, in worst case scenarios more than doubling the amount of work needed or more. While easy to use, the function is also prone to confusion and problems later on. See the note further below on caveats for details.

For general post queries, use WP_Query or get_posts() .

It is strongly recommended that you use the ‘pre_get_posts’ action instead, and alter the main query by checking is_main_query() .

For example, on the homepage, you would normally see the latest 10 posts. If you want to show only 5 posts (and don’t care about pagination), you can use query_posts() like so:

Here is similar code using the ‘pre_get_posts’ action in functions.php :

Usage

Place a call to query_posts() in one of your Template files before The Loop begins. The WP_Query object will generate a new SQL query using your parameters. When you do this, WordPress ignores the other parameters it receives via the URL (such as page number or category).

Preserving Existing Query Parameters

If you want to preserve the original query parameter information that was used to generate the current query, and then add or over-ride some parameters, you can use the $query_string global variable in the call to query_posts() .

For example, to set the display order of the posts without affecting the rest of the query string, you could place the following before The Loop:

When using query_posts() in this way, the quoted portion of the parameter must begin with an ampersand (&).

Or alternatively, you can merge the original query array into your parameter array:

Combining Parameters

You may have noticed from some of the examples above that you combine parameters with an ampersand (&), like so:

Posts for category 13, for the current month on the main page:

At 2.3 this combination will return posts belong to both Category 1 AND 3, showing just two (2) posts, in descending order by the title:

The following returns all posts that belong to category 1 and are tagged “apples”.

You can search for several tags using “+”. In this case, all posts belong to category 1 and tagged as “apples” and “oranges” are returned.

Caveats

query_posts() is only one way amongst many to query the database and generate a list of posts. Before deciding to use query_posts() , be sure to understand the drawbacks.

Alters Main Loop

query_posts() is meant for altering the main loop. It does so by replacing the query used to generate the main loop content. Once you use query_posts() , your post-related global variables and template tags will be altered. Conditional tags that are called after you call query_posts() will also be altered – this may or may not be the intended result.

Secondary Loops

To create secondary listings (for example, a list of related posts at the bottom of the page, or a list of links in a sidebar widget), try making a new instance of WP_Query or use get_posts() .

If you must use query_posts() , make sure you call wp_reset_query() after you’re done.

Pagination

Pagination won’t work correctly, unless you set the ‘paged’ query var appropriately: adding the paged parameter

Additional SQL Queries

If you use query_posts within a template page, WordPress will have already executed the database query and retrieved the records by the time it gets to your template page (that’s how it knew which template page to serve up!). So when you over-ride the default query with query_posts() , you’re essentially throwing away the default query and its results and re-executing another query against the database.

This is not necessarily a problem, especially if you’re dealing with a smaller blog-based site. Developers of large sites with big databases and heavy visitor traffic may wish to consider alternatives, such as modifying the default request directly (before it’s called). The ‘request’ filter can be used to achieve exactly this.

The ‘parse_query’ and the ‘pre_get_posts’ filters are also available to modify the internal $query object that is used to generate the SQL to query the database.

Resources

  • For more in-depth discussion of how WordPress generates and handles its queries, review these articles: Query Overview and Custom Queries
  • Customize the Default Query properly using ‘pre_get_posts’ – Bill Erickson – Customize the WordPress Query or John James Jacoby – Querying Posts Without query_posts
  • You don’t know Query – Slides from WordCamp Netherlands 2012 by Andrew Nacin

Source

Uses

Changelog

Uses Description
WP_Query::__construct() wp-includes/class-wp-query.php
Changelog
Version Description
1.5.0 Introduced.

User Contributed Notes

Override the main query with all posts in a 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:

This will return ALL posts from the category. If you have a lot of posts (see: thousands), using a realistically high number instead of -1 for performance reasons.

However, for subcategories (or child categories), category_name doesn’t always work. Rather use category-slug instead. See is_category().

The same precautions apply when using -1.

Passing variables to query_posts
You can pass a variable to the query with several methods, depending on your needs. As with other examples, place these above your Loop:

In this example, we concatenate the query before running it. First assign the variable, then concatenate and then run it. Here we’re pulling in a category variable from elsewhere.

In this next example, the double quotes tell PHP to treat the enclosed as an expression. For this example, we are getting the current month and the current year, and telling query_posts() to bring us the posts for the current month/year, and in this case, listing in ascending order so we get the oldest post at the top of the page.

This example explains how to generate a complete list of posts, dealing with pagination. We can use the default $query_string telling query_posts() to bring us a full posts listing. We can also modify the posts_per_page query parameter from -1 to the number of posts you want to show on each page; in this last case, you’ll probably want to use posts_nav_link() to navigate the generated archive.

If you don’t need to use the $query_string variable, another method exists that is more clear and readable, in some more complex cases. This method puts the parameters into an array. The same query as in Example 2 above could be done like this:

As you can see, with this approach, every variable can be put on its own line, for easier reading.

It is even possible to use the array style (Example 4) to query multiple taxonomies. Simply supply the taxonomy slug with a string of comma-separated values (each value being one term). In the example below, we will get all movie posts starring either Bruce Campbell or Chuck Norris.

Exclude Categories From Your Home Page
Placing this code in index.php file will cause the home page to display posts from all categories except category ID 3.

You must log in before being able to contribute a note or feedback.

Источник

Читайте также:  Как установить драйвер для принтера samsung ml 1610
КомпСовет