1

这应该很简单,但我无法找到正确语法的一个很好的例子来做到这一点。

我想按 meta_queries 过滤我的帖子,但按指定的 meta_key 对它们进行排序。

当我按原样运行代码时,它会导致无限循环。我只包含了问题代码,其他代码是您运行 query_post 的基本循环代码。

此外,所有 PHP 变量都是正确的,不是问题。

        $args2 = array(
            'meta_key' => '_count-views_all',
            //'meta_value' => $id,
            'orderby' => 'meta_value_num',
            'order' => $sortOrder,
            'posts_per_page' => 9,
            'paged' => $paged,
            'meta_query' => array(  
                        'relation' => 'OR',
                        array(
                            'key' => 'contributorid1',
                            'value' => $id,
                            'compare' => '='
                            ),

                        array(
                            'key' => 'contributorid2',
                            'value' => $id,
                            'compare' => '='
                            )
                        )
        );
        $posts = query_posts($args2); 
    }

这是另一个完全没有交叉引用问题的查询。两者在同一页面上运行,但嵌套在 if else 语句中

        $args1 = array(
            //'meta_key' => 'contributorid1',
            //'meta_value' => $id,
            'order' => $sortOrder,
            'orderby' => 'title',
            'posts_per_page' => 9,
            'paged' => $paged,
            'meta_query' => array(
                        'relation' => 'OR',
                        array(
                            'key' => 'contributorid1',
                            'value' => $id,
                            'compare' => '='
                            ),

                        array(
                            'key' => 'contributorid2',
                            'value' => $id,
                            'compare' => '='
                            )
                        )
        );
        $posts = query_posts($args1);
4

1 回答 1

1

The query looks reasonable to me. The only method by which I see this running into an infinite loop is if this query runs within the post loop. When you use query_posts as you are, it will change the state of the global $wp_query, which is used for the pointer in the main posts loop.

If it kept hitting query_posts within the loop, it would continually change the state of the global $wp_query object, and reset the pointer for the current post to the first post of that new query, which would ultimately create the infinite loop.

If this code is being used within the loop, I'd recommend instead using something like

$query = new WP_Query($args2);
if ($query->have_posts()) { ... etc; }

If you need to then set up global post data within it, be sure to use wp_setup_postdata or $query->the_post() and wp_reset_postdata or wp_reset_query appropriately when you are finished using that post as the global post information.

于 2013-01-02T20:48:35.653 回答