Why posts array is empty?

时间:2012-12-26 作者:Stephan

我尝试获取没有自定义字段集的帖子,或者if set的值与给定的参数不同。

这是我的代码:

    $args_included = array(
        \'numberposts\'     => 1,
        \'post_type\'       => \'post\',
        \'post_status\'     => \'published\',
        \'meta_query\' => array(
               \'relation\' => \'OR\',
                array(
                    \'key\' => \'requested_by\',
                    \'value\' => \'%\' . $SANITIZED_PARAM . \'%\',
                    \'compare\' => \'NOT LIKE\'
                ),
                array(
                    \'key\' => \'requested_by\',
                    \'compare\' => \'NOT EXISTS\'
                )
        )
    );

    get_posts($args_included); // empty array
自定义字段requested_by 应为空或用如下字符串值填充:foo;bar;gamma;.

如果我删除这部分代码:

                \'relation\' => \'OR\',
                array(
                    \'key\' => \'requested_by\',
                    \'value\' => \'%\' . $SANITIZED_PARAM . \'%\',
                    \'compare\' => \'NOT LIKE\'
                ),
然后查询就可以工作了。

我错过了什么?

WP 3.5

UPDATE以下是我的最终代码:

    $args_included = array(
        \'numberposts\'     => 1,
        \'post_type\'       => \'post\',
        \'post_status\'     => \'publish\',
        \'meta_query\' => array(
                array(
                    \'key\' => \'requested_by\',
                    \'value\' => $PARAM,
                    \'compare\' => \'NOT LIKE\'
                )
        )
    );

    get_posts($args_included); // Just ONE post
错误:

状态为publishpublished下面是针对批量设置自定义字段的SQL查询:

INSERT INTO wp_postmeta(post_id,meta_key,meta_value)
   SELECT ID , \'requested_by\', \';\'
   FROM wp_posts
   WHERE post_status=\'publish\'
   AND post_type=\'post\'
最后的调试提示。您可以将最终SQL查询发送到MySQL,如下所示:

$args = array(
    \'numberposts\'     => 1,
    \'post_type\'       => \'post\',
    \'post_status\'     => \'publish\',
    \'meta_query\' => array(
            array(
                \'key\' => \'requested_by\',
                \'value\' => $PARAM,
                \'compare\' => \'NOT LIKE\'
            )
    )
);

$q = new WP_Query($args);
echo $q->request;

1 个回复
最合适的回答,由SO网友:Otto 整理而成

您不需要将%符号添加到值中。WordPress会在相似或不相似的比较中自动为您做到这一点。您也不需要“清理”参数,它将自动为SQL转义。

请参阅wp includes/meta。php,大约在第806行左右。

结束

相关推荐

Refine custom posts by author

我想有一种为特定作者显示自定义后期存档的方法。我能够显示某个类别的自定义帖子,但不仅仅是作者的自定义帖子。我已经有了一个单独的作者页面模板,显示他们写的所有帖子,按帖子类型划分。我使用以下方式查询此信息:query_posts( array( \'post_type\' => \'custom_post_name\', \'author\'=>$curauth->ID ) ); while (have_p