仅当meta_value不为空时,我才能显示帖子
题
三个人已经试图解决这个问题,我们正在零零。我只想显示在meta_key'tapered_image'中具有价值的帖子。
因此,...如果“特色_image”不是空的,请显示帖子。这是代码:
<ul>
<?php
$args = array(
'showposts' => 5,
'meta_query' => array(
array(
'key' => 'featured_image',
'value' => '',
'compare' => '!='
)
)
);
$ft_pagination = new WP_Query( $args );
?>
<?php while ($ft_pagination->have_posts()) : $ft_pagination->the_post(); ?>
<?php $ftimage = get_post_meta(get_the_id(), 'featured_image', TRUE); ?>
<li>
<article>
<a href="">
<?php if ($ftimage): ?>
<img src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=<?php echo $ftimage; ?>&w=84&h=60" alt="" />
<?php else: ?>
<img src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=/wp-content/themes/ssv/images/review-default.gif&w=84&h=60" alt="" />
<?php endif; ?>
</a>
</article>
</li>
<?php
endwhile;
wp_reset_query();
?>
</ul>
我们已经尝试了我们能想到的每种组合,弃用的meta_*选项,query_posts,get_posts,而不是wp_query ...什么都没有。打印了Select语句,未显示元值字段。它存在 - 对于帖子(对于每个帖子),并且存在于DB中。
我们现在已经看到了有关该主题的每个帖子,包括以下内容:
http://scribu.net/wordpress/advanced-metadata-queries.html
Zilch。请帮忙...
解决方案
你好 @抢:
您无法弄清楚该怎么做的原因是因为它是不可能的,至少不是不诉诸SQL。尝试将以下内容添加到您的主题 functions.php
文件:
add_filter('posts_where','yoursite_posts_where',10,2);
function yoursite_posts_where($where,$query) {
global $wpdb;
$new_where = " TRIM(IFNULL({$wpdb->postmeta}.meta_value,''))<>'' ";
if (empty($where))
$where = $new_where;
else
$where = "{$where} AND {$new_where}";
return $where;
}
如果您有自定义 'featured_image'
具有空值的字段将过滤掉它们。如果您出现问题是其他的,我们必须查看您的数据如何解决。
我很好奇的一件事;您如何获得空的值 'featured_image'
? WordPress 3.1中的Admin UI尽力使您避免输入空值。希望这可以帮助。
其他提示
这似乎可以使该值进入查询,但不确定是否会提取有效的结果。
'meta_query' => array(
array(
'key' => 'some_key',
'value' => array(''),
'compare' => 'NOT IN'
)
)
没有时间创建字段来测试结果,但是我一直在看我今天使用的查询,并注意到 NOT IN
会很高兴地取一个空数组。
这是一个古老的问题,但似乎WordPress修复了此“缺失功能”:现在,根据 WordPress法典 可以检查元密钥的存在(或不存在)
'meta_query' => array(
array(
'key' => 'featured_image',
'compare' => 'EXISTS', //or "NOT EXISTS", for non-existance of this key
)
)
这是从WP> = 3.5开始的。
这是对我有用的查询。与T31OS回答的比较非常相似,但是由于元密钥/值只是一个简单的文本串,因此它不需要是元_Query数组。
$args = array(
'posts_per_page' => 5,//replaced 'showposts' in version 2.1
'meta_key' => 'featured_image',
'meta_value' => array(''),
'meta_compare' => 'NOT IN'
);
无论出于何种原因,使用 'meta_value'=>'' 和 'meta_compare'=>'!=' 或者 'meta_compare'=>'不喜欢' 仍然为我提取所有帖子,但这可能与我使用高级自定义字段(ACF)插件创建的元值有关。
这是在WP 3.2-Alpha中固定的:
我想念什么吗?
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'meta_key' => "featured_image"
);
$the_query = new WP_Query( $args );
?>
那不这样做吗?
!has_featured_image();
一个衬里ftw。