列出多个 $query->set 的正确方法 [英] Correct way to list multiple $query->set
问题描述
列出多个 $query->set 的正确方法是什么?我可以有多个 $query->set
像下面的CODE A"吗?
还是我应该将它们合二为一?如果是,您将如何组合三个 $query->set
代码?我尝试将它们组合在下面的CODE B"中,但没有用.
What is the correct way to list multiple $query->set ? Am I allowed to have multiple $query->set
like "CODE A" below ?
Or am I supposed to combine them into one? If yes, how would you combine the three $query->set
code? I tried combining them in "CODE B" below but it didn't work.
.
代码 A:在组合 $query->set 之前
这段代码在functions.php中
This code goes in functions.php
function featured_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'category_name', 'new' );
$query->set( 'cat', '-60, -61' );
$query->set( 'posts_per_page', 5 );
}
}
add_action( 'pre_get_posts', 'featured_category' );
.
CODE B:合并后 $query->set
这段代码在functions.php中
This code goes in functions.php
function featured_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( array( 'category_name' => 'new', 'cat' => '-60, -61', 'posts_per_page' => 5) );
}
}
add_action( 'pre_get_posts', 'featured_category' );
推荐答案
使用 set
方法(它是 WP_Query
类的一部分)的正确方法是传递 2 个参数 - 一个查询参数键和一个查询参数值.所以你的第一个例子(代码 A)是正确的方法.
The correct way to use the set
method (which is part of the WP_Query
class) is to pass 2 parameters - a query parameter key and a query parameter value. So your first example (CODE A) is the correct way to do it.
你可以在这里查看方法代码:https://core.trac.wordpress.org/browser/tags/4.0/src/wp-includes/query.php#L2328
You can take a look at the method code here: https://core.trac.wordpress.org/browser/tags/4.0/src/wp-includes/query.php#L2328
附言如果要从查询中排除多个类别,请考虑使用 category__not_in
查询参数,例如:
P.S.
If you want to exclude multiple categories from a query, consider using the category__not_in
query parameters, for example:
$query->set( 'category__not_in', array(60, 61) );
有关类别查询参数的更多信息,请查看http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
For more information about category query parameters, check http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
这篇关于列出多个 $query->set 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!