SQL查询仅将具有自定义字段的帖子添加到数组

时间:2012-08-08 作者:fightstarr20

我有一个SQL查询,它正在构建一个wordpress帖子数组。。。

$query = "select $wpdb->posts.* from $wpdb->posts,$wpdb->terms,$wpdb->term_taxonomy,$wpdb->term_relationships where $wpdb->terms.term_id in (".$catId.") and $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id and $wpdb->term_taxonomy.taxonomy = \'pcategory\' and $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id AND $wpdb->posts.post_status = \'publish\' and $wpdb->term_relationships.object_id = $wpdb->posts.ID and $wpdb->posts.ID != ".$post->ID." group by $wpdb->posts.ID order by $wpdb->posts.ID LIMIT 0 ,$limit";
我需要对此进行修改,以允许我添加一个条件,即数组中只包含具有特定自定义字段值的帖子,例如“Apple”。

有人能给我指出正确的方向吗?

更新我已尝试将其修改为。。。。

$query = "select $wpdb->posts.* from $wpdb->posts,$wpdb->terms,$wpdb->term_taxonomy,$wpdb->term_relationships where $wpdb->terms.term_id in (".$catId.") and $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id and $wpdb->term_taxonomy.taxonomy = \'pcategory\' and $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id AND $wpdb->posts.post_status = \'publish\' and $wpdb->postmeta.meta_key = \'fruit\' and $wpdb->postmeta.meta_value= \'apple\' and $wpdb->term_relationships.object_id = $wpdb->posts.ID and $wpdb->posts.ID != ".$post->ID." group by $wpdb->posts.ID order by $wpdb->posts.ID LIMIT 0 ,$limit";
我假设这将缩小搜索范围,只搜索名为“fruit”的自定义字段值为“apple”但不起作用的帖子

1 个回复
SO网友:westondeboer

你为什么不:

<?php 
global $post;
$args = array( 
    \'post_type\' => \'post\',
    \'post_status\' = \'publish\',
    \'posts_per_page\' => \'10\',
    \'meta_query\' => array(
        array(
            \'key\' => \'fruit\',
            \'value\' => \'apple\'
        )
    )
);
$custom_query = new WP_Query( $args );
while( $custom_query->have_posts() ): $custom_query->the_post(); ?>

<?php the_title(); ?>

<?php endwhile; wp_reset_query(); ?>

结束

相关推荐

Validate an option array

我们使用默认的WordPressregister_setting() 函数验证主题选项。此调用,例如:register_setting( \'options-group\', \'option1\', \'intval\' ); 将验证是否$option1 是一个整数。我可以使用什么传递选项数组来验证数组的每个成员?例如:$options = array( \'options1\' => 4, // intval \'options