問題描述

有三個人已經試圖解決這個問題,而且我們沒有了。我想只顯示在 meta_key ‘featured_image’ 中有值的帖子。

所以… 如果’featured_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 語句,沒有顯示元值欄位。它存在 – 對於帖子 (對於每個帖子),並且它存在於資料庫中。

我們已經看到了關於這個話題的每一篇文章,其中包括:

 query_posts and only show results if a custom field is not empty

 http://scribu.net/wordpress/advanced-metadata-queries.html

小人物。請幫忙…

最佳解決方案

嗨 @Rob:

你無法弄清楚如何做的原因是因為這是不可能的,至少不是沒有訴諸於 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 中的管理介面儘可能避免您輸入空值。希望這可以幫助。

次佳解決方案

這似乎有助於獲取查詢的價值,不知道是否拉取有效的結果..

'meta_query' => array(
    array(
        'key' => 'some_key',
        'value'   => array(''),
        'compare' => 'NOT IN'
    )
)

沒有時間建立欄位來測試結果,但是我一直在觀看我今天所使用的查詢,並注意到 NOT IN 將樂意採取一個空陣列。

第三種解決方案

這在 WP 3.2-alpha 中是固定的:

 http://core.trac.wordpress.org/ticket/15292

第四種方案

我錯過了什麼嗎?

<?php
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => -1,
        'meta_key' => "featured_image"
    );
    $the_query = new WP_Query( $args );

?>

不會這樣嗎?

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。