具有自定义字段元值的QUERY_POST

时间:2011-10-17 作者:Stickers

我有以下要求:

如果子页面featured_product 值等于1 然后就是特色节目。这是可行的。

如果子页面featured_product 并且该值不等于1, 或者如果连场地都没有featured_product 那就不是特色产品了。这目前不起作用。

对于特色产品(它有效):

<?php 
    query_posts(
        array(
            \'showposts\'   => -1, 
            \'post_parent\' => $post->ID, 
            \'post_type\'   => \'page\', 
            \'orderby\'     => \'title\',
            \'order\'       => \'ASC\', 
            \'meta_key\'    => \'featured_product\', 
            \'meta_value\'  => 1
        )
    );
?>
对于普通产品(不起作用):

<?php 
    query_posts(
        array(
            \'showposts\'    => -1, 
            \'post_parent\'  => $post->ID, 
            \'post_type\'    => \'page\', 
            \'orderby\'      => \'title\', 
            \'order\'        => \'ASC\', 
            \'meta_key\'     => \'featured_product\', 
            \'meta_compare\' => \'!=\', 
            \'meta_value\'   => 1
        )
    );
?>

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

我找到的查询meta\\u键所在帖子的最佳解决方案IS NOT 或不存在的是使用posts_where 使用小子查询筛选,请尝试以下操作:

//paste this function in your theme\'s functions.php

function metakey_no_featured( $where )
{
    global $wp_query;
    global $wpdb;
    $where .= $wpdb->prepare(" AND $wpdb->posts.ID NOT IN ( SELECT post_id FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID) AND meta_key = %s AND meta_value = 1) ",\'featured_product\');

    return $where;
}


//and when you query none featured products use
add_filter(\'posts_where\', \'metakey_no_featured\' );
query_posts(
        array(
            \'showposts\'    => -1, 
            \'post_parent\'  => $post->ID, 
            \'post_type\'    => \'page\', 
            \'orderby\'      => \'title\', 
            \'order\'        => \'ASC\', 
        )
    );
remove_filter(\'posts_where\', \'metakey_no_featured\' );

结束

相关推荐