WP归档按自定义元键

时间:2015-05-20 22:43:58

标签: php wordpress

在Wordpress模板的 function.php 下面的代码运行良好

// Function accepting current query
function my_change_order( $query ) {
    // Check if the query is for an archive
    if($query->is_archive())
        // Query was for archive, then set order
        $query->set( 'order' , 'asc' );
    // Return the query (else there's no more query, oops!)
    return $query;
}
// Runs before the posts are fetched
add_filter( 'pre_get_posts' , 'my_change_order' );

但我需要通过_my_meta_vip之类的自定义元键订购文章。基于this answer我尝试了以下几行,但只获得了一半成功,因为只加载了定义了自定义元键的文章,其他文章丢失了。我该如何解决?

function my_change_order( $query ) {
    if($query->is_archive())
        $query->set( 'orderby' , 'meta_value' );
        $query->set( 'meta_key' , '_my_meta_vip' );
    return $query;
}
add_filter( 'pre_get_posts' , 'my_change_order' );

如何通过自定义元键正确订购文章?

3 个答案:

答案 0 :(得分:2)

   function my_change_order( $query ) {
        // Check if the query is for an archive
        if($query->is_archive())
        // Query was for archive, then set order
        $query->set( 'order' , 'asc' );
        $query->set( 'meta_query', array(
            array(
              'key' => '_my_meta_vip'
            )
        ));

        // Return the query (else there's no more query, oops!)
        return $query;
    }

查看以下主题:https://wordpress.stackexchange.com/questions/20237/using-meta-query-how-can-i-filter-by-a-custom-field-and-order-by-another-one可能会给您一个清晰的想法

答案 1 :(得分:1)

最后无法找到任何方式列出所有已定义_my_meta_VIP的帖子。

在我的解决方案中,所有_my_meta_VIP都填充了enableddisabled,以下代码执行此任务:

    // Function accepting current query
    function my_change_order( $query ) {
        // Check if the query is for an archive
        if($query->is_archive()) {
            // Query was for archive, then set order
            $query->set( 'post_type', 'profile' );
            $query->set( 'orderby' , 'meta_value' );
            $query->set( 'meta_key' , '_my_meta_vip' );
            $query->set( 'order', 'DESC' );
        } else {
            // Return the original query for non-archive pages
            return $query;
        }
        // Return the query
        return $query;
    }
    // Runs before the posts are fetched
    add_filter( 'pre_get_posts' , 'my_change_order' );

答案 2 :(得分:0)

这里的基本问题似乎是查询在帖子和帖子表上进行内部联接,这就是为什么没有特定帖子元条目的帖子不会被返回的原因查询。你想要的是一个左连接。有关差异的解释,请参阅this answer

您应该可以使用posts_join过滤器将内部联接替换为左联接:

add_filter('posts_join', function($join) {
    global $wpdb;

    // Replace inner join with left join
    $search = 'INNER JOIN ' . $wpdb->postmeta;
    $replace = 'LEFT JOIN ' . $wpdb->postmeta;
    $join = str_ireplace($search, $replace, $join);

    return $join;
});