Custom Query Arguments

时间:2012-12-27 作者:Khan

我想基于以下$参数运行查询。我的问题是如何将可变数量的数组传递给tax\\u query,因为目前tax\\u query中有两个数组,可以是1、3或5,依此类推。有没有可能?

$args = array (
            \'posts_per_page\' => 10,
            \'tax_query\' => array(
                \'relation\' => \'OR\',
                array(
                    \'taxonomy\' => $Tax[0],
                    \'field\' => \'slug\',
                    \'terms\' => array( $Tag )
                ),
                array(
                    \'taxonomy\' => $Tax[1],
                    \'field\' => \'slug\',
                    \'terms\' => array( $Tag )

                )
            ),
            \'order\' => \'DESC\'

        );

2 个回复
SO网友:Selva Balaji
/**
 * Define a new function that uses $args and wp_parse_args()
 */
function explain_parse_args( $args ) {
    $defaults = array (
        \'text\' => \'wp_parse_args() merges $args into $defaults\',
        \'before\' => "

", \'after\' => "

\\n", \'echo\' => TRUE ); // Parse incomming $args into an array and merge it with $defaults $args = wp_parse_args( $args, $defaults ); // OPTIONAL: Declare each item in $args as its own variable i.e. $type, $before. extract( $args, EXTR_SKIP ); $output = $before . $text . $after; if (!$echo) return $output; echo $output; } /** * Run our new function using the defaults (no $args) * This would print out: *

wp_parse_args() merges $args into $defaults

*/ explain_parse_args(); /** * Run the function with some options overriden with an array * This would echo the output with the modified text and before arguments: * A better explanation

*/ explain_parse_args( array ( \'text\' => "A better explanation", \'before\' => "" ) ); /** * We can also pass in URL-style string-query and it will be converted * This would set $args[\'echo\'] to 1 and $args[\'text\'] to 0 */ explain_parse_args( \'echo=1&text=0\' );
SO网友:admcfajn

我会这样做:

$args = array (
  \'posts_per_page\' => 10,
  \'order\' => \'DESC\'
);
$tax_query = array(\'relation\' => \'OR\');

for($i=0;$i<count($Tax),$i++){
  array_push($tax_query, array(
    \'taxonomy\' => $Tax[$i],
    \'field\' => \'slug\',
    \'terms\' => array( $Tag )
  ));
}

$args[\'tax_query\'] = $tax_query;
使用速记数组大括号可能更清晰:

$args = [
  \'posts_per_page\' => 10,
  \'order\' => \'DESC\'
];

$tax_query = [\'relation\' => \'OR\'];

for($i=0;$i<count($Tax),$i++){
  $tax_query[] = [
    \'taxonomy\' => $Tax[$i],
    \'field\' => \'slug\',
    \'terms\' => array( $Tag )  
  ];
}

$args[\'tax_query\'] = $tax_query;

结束

相关推荐

如何将WP_QUERY与多个帖子ID一起使用?

我想用ID数组查询多篇文章(注意:我正在查询自定义文章类型)。以下是我所拥有的不起作用的东西:$myarray = array(144, 246); $args = array( \'post_type\' => \'ai1ec_event\', \'p\' => $myarray ); // The Query $the_query = new WP_Query( $args ); 有什么建议吗?