2013-04-30 30 views
1

我目前正在開發一個小型博客,其中有一個顯示所有「特殊項目」的邊欄。通過meta和發佈日期排序WP_Query

「特殊項目」只是一個類別,側邊欄將一次只顯示4個帖子,按發佈日期過濾,但我也有一個自定義元框允許用戶發佈帖子。 這些特色帖子應該顯示在特殊項目的頂部。

現在我的查詢是這樣的:

new WP_Query("showposts=" . $instance['num'] . "&cat=" . $instance["cat"] . "&order=ASC&order_by=date") 

我能得到這樣的功能的元數據:

$featured = get_post_meta($single_cat_post->ID, 'soy_featured_post', true); 

但我怎麼能融入這個WP_Query裏面?

回答

3

首先,'showposts'在使用WP_Query時已被'posts_per_page'取代。我在你的代碼中糾正了這個問題。此外,在一個循環內,您應該只能使用$ post-> ID而不是$ single_cat_post-> ID。

我會使用兩個循環。設置參數,然後在第一個循環中包含檢查元值的條件,重置查詢,然後執行另一個循環幷包含檢查元值的條件,如果存在則輸出任何內容。

在第一個查詢中,我添加了一個檢查來查看第一個循環返回多少帖子。然後使用該值(減去4),我計算了一個變量用於第二個循環中的posts_per_page。然後,我添加了一個條件,只有在結果大於0時才運行循環。

這是未經測試的,但它應該起作用或至少將您置於正確的道路上!

<?php 
$args = array(
    'posts_per_page' => 4, 
    'meta_key' => 'soy_featured_post', 
    'cat' => $instance["cat"], 
    'orderby' => 'date', 
    'order' => 'ASC' 
); 

$special_post_query = new WP_Query($args); 
$special_posts_found = $special_post_query->found_posts; 

if ($special_post_query->have_posts()) : 
    while($special_post_query->have_posts()) : $special_post_query->the_post(); 

    // POST WITH META VALUE OUTPUT 
    the_title(); 

    endwhile; 
endif; 

wp_reset_query(); 

$second_loop_posts_per_page = 4 - $special_posts_found; 

if ($second_loop_posts_per_page > 0) { 
    $args = array(
     'posts_per_page' => $second_loop_posts_per_page, 
     'cat' => $instance["cat"], 
     'orderby' => 'date', 
     'order' => 'ASC' 
    ); 

    if ($special_post_query->have_posts()) : 
     while($special_post_query->have_posts()) : $special_post_query->the_post(); 

     // Condition to test for NO meta value 
     if (get_post_meta($post->ID, 'soy_featured_post', true) == null) { 
      // CODE 
      the_title(); 
     } else { 
      // Don't print anything because the meta value exists 
     } 

     endwhile; 
    endif; 

    wp_reset_query(); 
} ?>