2017-01-30 14 views
1

我有一個WooCommerce商店,我想顯示如下(按順序)中的一個特色形象&標題:如何編寫空wp_query更高效的回退在WordPress的

  1. 特色產品
  2. 如果沒有特色產品,然後粘後
  3. 如果沒有粘後,則最近張貼

但我也想寫高效的代碼。我如何簡化這個並刪除多餘的PHP和HTML?

/* START FEATURED PRODUCT QUERY */ 
$args = array(
    'posts_per_page' => 1, 
    'post_type' => 'product', 
    'meta_query' => array(
     'key' => '_featured', 
     'value' => 'yes' 
     ), 
$query = new WP_Query($args); 

if($query->have_posts()) { 
    while($query->have_posts()) { 
      $query->the_post(); ?> 

      <a href="<?php the_permalink(); ?>" id="featured-blog-post">  
       <?php the_post_thumbnail('full'); 
      the_title('<h2>', '<span>&raquo;</span></h2>'); 
      the_excerpt(); ?> 
      </a> <?php 
    } // end while 
    wp_reset_postdata();   
} else { 

/* START FALLBACK POST QUERY */ 
$args = array(
    'posts_per_page' => 1, 
    'post__in' => get_option('sticky_posts'), 
    'ignore_sticky_posts' => 1 
    ); 

$query = new WP_Query($args); 

    while($query->have_posts()) { 
      $query->the_post(); ?> 

      <a href="<?php the_permalink(); ?>" id="featured-blog-post">  
       <?php the_post_thumbnail('full'); 
      the_title('<h2>', '<span>&raquo;</span></h2>'); 
      the_excerpt(); ?> 
      </a> <?php 
    } // end while 
    wp_reset_postdata(); 
}  

第二WP_Query具有完全相同的HTML輸出,只是不同$args

回答

0

我正在寫一個類似的查詢,我不知道,你可以讓查詢更有效的WordPress的比你已經有。我做的唯一不同的是讓帖子的輸出成爲一個函數,以便它調用相同的代碼。這會更容易更新。

此外,由於您只是查詢第一個查詢中的一個元字段,我切換到一個簡單的自定義字段查詢。

// Function to output posts 
function output_posts($query){ 

    while($query->have_posts()) { 
     $query->the_post(); 

     echo '<a href="' . get_permalink() '" id="featured-blog-post">';  
      the_post_thumbnail('full'); 
      the_title('<h2>', '<span>&raquo;</span></h2>'); 
      the_excerpt(); 
     echo '</a>'; 
    } 

    wp_reset_postdata();  
} 

// Featured query 
$args = array(
    'posts_per_page' => 1, 
    'post_type'  => 'product', 
    'meta_key'  => '_featured', 
    'meta_value'  => 'yes', 
); 

$featured = new WP_Query($args); 

// If featured has posts 
if($featured->have_posts()) { 
    // Output 
    output_posts($featured);  

// Else fallback  
} else { 

    // Fallback query 
    $args = array(
     'posts_per_page'  => 1, 
     'post__in'   => get_option('sticky_posts'), 
     'ignore_sticky_posts' => 1, 
    ); 

    $fallback = new WP_Query($args); 

    // If fallback has posts 
    if ($fallback->have_posts()){ 
     // Output 
     output_posts($fallback);  

    } 
}