Filter taxonomies using WP_Query parameter

王林
Release: 2023-09-01 15:50:01
Original
1573 people have browsed it

So far in this series, you have learned about the structure of WP_Query and its properties and methods. Now we are looking at the various parameters that can be used with WP_Query and how to encode them.

WP_Query has a large number of possible parameters, which makes it extremely flexible. Since you can use it to query any content held in the wp_posts table, it has parameters for every permutation of the query you might want to run on the content.

In this tutorial, I will learn about the parameters for querying classification terms.

  • Classification parameters
  • Query a classification term
  • Query multiple terms in a category
  • Query terms from multiple categories
  • Nested classification query

Review of how parameters work in phpcnc phpcn>WP_Query

Before we begin, let's quickly review how parameters work in WP_Query. When you write a WP_Query in your theme or plugin, you need to include four main elements:

  • Query parameters, use the parameters that will be introduced in this tutorial
  • The query itself
  • cycle
  • End: Close if and class="inline">while tags and reset post data

In practice, this will look something like the following:

<?php

$args = array(
    // Arguments for your query.
);

// Custom query.
$query = new WP_Query( $args );

// Check that we have query results.
if ( $query->have_posts() ) {

    // Start looping over the query results.
    while ( $query->have_posts() ) {

        $query->the_post();

        // Contents of the queried post results go here.

    }

}

// Restore original post data.
wp_reset_postdata();

?>
Copy after login

These parameters tell WordPress what data to get from the database, which I will cover here. So what we're focusing on here is the first part of the code:

$args = array(
    // Arguments for your query.
);
Copy after login

As you can see, the parameters are contained in an array. As you follow this tutorial, you'll learn how to code them.

Write your parameters

The parameters in the array have a specific encoding method, as follows:

$args = array(
    'parameter1' => 'value',
    'parameter2' => 'value',
    'parameter3' => 'value'
);
Copy after login

You must enclose parameters and their values ​​in single quotes, use => between them, and separate them with commas. If you make this mistake, WordPress may not add all parameters to the query, otherwise you may see a white screen.

Classification parameters

Since you are using tax_query, setting parameters for taxonomy terms is a bit more complicated than setting parameters for categories and tags. In this parameter, you can write a nested array of parameters to specify taxonomies and terms using:

  • Classification (String): Classification
  • field (string): Select the classification term ('term_id (default), 'name' or 'slug')
  • terms (int/string/array):Classification terms
  • include_children (Boolean value): Whether to include children of the hierarchical taxonomy. Defaults to true.
  • operator (string): The operator to test. Possible values ​​are 'IN' (default), 'NOT IN', 'AND', 'EXISTS', and "does not exist".

The fact that you have the operator parameter means that you don't have to choose from a range of available parameters to define whether to include or exclude terms (as you do for labels and categories), but tax_query can be used instead for all classification related content.

If you want to query multiple taxonomies, you can also use the relation parameter before all arrays (one for each taxonomy) where AND or OR Specify whether you want to find posts containing all terms or any of them.

This can be easily explained with some examples.

Query a classification term

This is the simplest scenario, involving only the use of a nested array:

$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => 'tutorial',
        )
    )
);
Copy after login

Filter taxonomies using WP_Query parameter

The above query is for posts containing the term tutorial in the category category. Note that you also need to use the field parameter to identify which field you are using to identify the term, unless you are using the default term ID. If you want to use the term ID, you can use something like this:

$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'terms' => '11'
        )
    )
);
Copy after login

Filter taxonomies using WP_Query parameter

Using IDs makes it harder to determine what the query is looking for later, but can avoid any potential problems if you think users might edit the term slugs.

Query multiple terms in a category

If you want to identify posts with one or more arrays of terms in the same category, you can still write a nested array but add a set of terms.

例如,要查询包含分类中任何术语 ID 列表的帖子,您可以使用:

$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'post_tag',
            'terms' => [14, 17]
        )
    )
);
Copy after login

Filter taxonomies using WP_Query parameter

但是如果您想查询包含这些术语的所有帖子怎么办?您需要在嵌套数组中使用 operator 参数:

$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'post_tag',
            'terms' => [14, 17],
            'operator' => 'AND'
        )
    )
);
Copy after login

Filter taxonomies using WP_Query parameter

请注意,第一个示例实际上使用 IN 运算符来查找包含任何术语的帖子,但由于这是默认值,因此您不必在参数中指定它。

另一种情况是,如果您想要查询在一个分类中没有任何术语数组的帖子,您可以这样做:

$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'post_tag',
            'terms' => [14, 17],
            'operator' => 'NOT IN'
        )
    )
);
Copy after login

Filter taxonomies using WP_Query parameter

在这里,我将 AND 运算符替换为 NOT IN,这意味着 WordPress 将查找数组中不包含任何术语的帖子。

请注意,如果您更喜欢使用 slugs 而不是术语 ID,则可以在任何这些场景中执行此操作。最后一个示例如下所示:

$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'post_tag',
            'field' => 'slug',
            'terms' => ['php', 'strings'],
            'operator' => 'NOT IN'
        )
    )
);
Copy after login

Filter taxonomies using WP_Query parameter

从多个分类中查询术语

如果您想要使用多个分类法,则需要创建多个数组。让我们看一个最简单的示例,查询包含类别分类中的一个术语标签分类中的一个术语的帖子:

$args = array(
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => ['tutorial']
        ),
        array(
            'taxonomy' => 'post_tag',
            'field' => 'slug',
            'terms' => ['javascript']
        )
    )
);
Copy after login

Filter taxonomies using WP_Query parameter

在这里,我编写了两个嵌套数组:每个分类法一个,使用与仅使用一种分类法的示例相同的参数。我在这些之前添加了 relation 参数。您需要包含 relation 参数来告诉 WordPress 是否正在查找每个数组输出的全部或部分帖子。其工作原理如下:

  • 如果您使用 'relation' => 'AND',WordPress 将获取第一个数组第二个数组中指定的帖子。因此,在上面的示例中,仅发布两者 类别中的 <code>tutorial slug 和 中的 <code class="inline">javascript slug post_tag 将被查询。
  • 如果您使用 'relation' => 'OR',WordPress 将获取第一个数组第二个数组输出的帖子。因此,在这种情况下,您将收到带有 tutorial slug 或 javascript slug(或两者)的帖子。

如果您正在寻找包含这两个标签之一的帖子,则可以使用以下代码:

$args = array(
    'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => ['tutorial']
        ),
        array(
            'taxonomy' => 'post_tag',
            'field' => 'slug',
            'terms' => ['javascript']
        )
    )
);
Copy after login

Filter taxonomies using WP_Query parameter

您还可以通过将给定分类法添加到数组中来查找多个术语:

$args = array(
    'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => ['guide']
        ),
        array(
            'taxonomy' => 'post_tag',
            'field' => 'slug',
            'terms' => ['php', 'strings']
        )
    )
);
Copy after login

Filter taxonomies using WP_Query parameter

通过将 relation 参数与查询相结合,并使用 operator 参数,您可以创建复杂的查询。下面的参数将查询包含一个分类中的术语但不包含另一个分类中的术语的帖子:

$args = array(
    'orderby' => 'title',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => ['tutorial'],
            'operator' => 'NOT IN'
        ),
        array(
            'taxonomy' => 'post_tag',
            'field' => 'slug',
            'terms' => ['php', 'math'],
            'operator' => 'AND'
        )
    )
);
Copy after login

Filter taxonomies using WP_Query parameter

请注意,我在这里使用了 'relation' => 'AND' :如果我使用 OR,它将使用 slug-two 没有 slug-one 的帖子,而不是有 slug-two 但没有 slug 的帖子-one,这就是我正在寻找的。

您可以根据需要进一步查询分类法的术语:在两个嵌套查询中使用 operator 参数,或添加额外的嵌套查询来查询另一个分类法中的术语。

嵌套分类查询

您可以创建嵌套分类查询来创建更复杂的过滤器来获取您的帖子。在 4.1 版本中,WordPress 核心添加了对嵌套分类法的支持。更早地获得类似的结果要么要复杂得多,要么根本不可能。

$args = array(
    'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => ['guide'],
        ),
        array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => ['tutorial'],
            ),
            array(
                'taxonomy' => 'post_tag',
                'field' => 'slug',
                'terms' => ['php', 'strings'],
                'operator' => 'AND'
            )
        )
    )
);
Copy after login

上述查询将选择 category 分类下带有 guide slug 的帖子,或者在 category 下具有 tutorial slug 并具有 php, stringsphpcnendc 的帖子<code>post_tag 下的 phpcn slug 组合.

Filter taxonomies using WP_Query parameter

关于 tax 参数的注释

您可能想知道为什么我没有包含 {tax} 参数,您只需按如下方式编写您的参数:

$args = array(
    'taxonomy1' => 'slug-one'
);
Copy after login

如果您过去曾经使用过这种查询分类法的方式,您可能会熟悉这种方式,但它现在已被弃用,并且您不应该使用它。所以坚持使用 tax_query!无论如何,使用 tax_query 会给您带来更大的灵活性。

摘要

查询分类比类别和标签稍微复杂一些,因为您需要掌握 tax_query 参数。

但是,正如我们所看到的,这是一个非常有力的论点,它为您提供了很大的范围和灵活性,可以按照您希望的方式查询数据库。

这篇文章已根据 Nitish Kumar 的贡献进行了更新。 Nitish 是一名 Web 开发人员,拥有在各种平台上创建电子商务网站的经验。他将业余时间花在个人项目上,让他的日常生活变得更轻松,或者在晚上与朋友一起散步。

The above is the detailed content of Filter taxonomies using WP_Query parameter. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!