2015-07-21 59 views
1

我想编辑WooCommerce Recent Products Shortcode,以便将查询限制为在过去15天内发布的产品。我不知道该怎么做。下面是短代码代码:如何编辑Woocommerce最近的产品简码,以便它只显示过去15天内发布的产品?

/** 
* Recent Products shortcode 
* 
* @param array $atts 
* @return string 
*/ 
public static function recent_products($atts) { 
    global $woocommerce_loop; 

    $atts = shortcode_atts(array(
     'per_page' => '12', 
     'columns' => '4', 
     'orderby' => 'date', 
     'order'  => 'desc' 
    ), $atts); 

    $meta_query = WC()->query->get_meta_query(); 

    $args = array(
     'post_type'    => 'product', 
     'post_status'   => 'publish', 
     'ignore_sticky_posts' => 1, 
     'posts_per_page'  => $atts['per_page'], 
     'orderby'    => $atts['orderby'], 
     'order'     => $atts['order'], 
     'meta_query'   => $meta_query 
    ); 

    ob_start(); 

    $products = new WP_Query(apply_filters('woocommerce_shortcode_products_query', $args, $atts)); 

    $columns = absint($atts['columns']); 
    $woocommerce_loop['columns'] = $columns; 

    if ($products->have_posts()) : ?> 

     <?php woocommerce_product_loop_start(); ?> 

      <?php while ($products->have_posts()) : $products->the_post(); ?> 

       <?php wc_get_template_part('content', 'product'); ?> 

      <?php endwhile; // end of the loop. ?> 

     <?php woocommerce_product_loop_end(); ?> 

    <?php endif; 

    wp_reset_postdata(); 

    return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>'; 
} 

我想,我需要以某种方式检索出版日期在循环的帖子,把在一个变量,并添加了一些检查,看看在while如果这个变量少于15天?这些步骤超出了我的能力。

回答

4

最好不要直接在核心中修改WooCommerce短代码。您需要删除他们的简码并添加自己的简码。或者现在我看起来更接近一些,我发现他们已经提供了用于修改查询参数的woocommerce_shortcode_products_query过滤器。

$products = new WP_Query(apply_filters('woocommerce_shortcode_products_query', $args, $atts)); 

接下来,你需要一些date parameters for WP_Query

当过滤woocommerce_shortcode_product_query ARGS可以设置date_query参数WP_Query

function so_31541643_recent_products_shortcode_args($args, $atts){ 

    $args['date_query'] = array(
     array(
      'after'  => '15 days ago', 
      'inclusive' => true, 
     ), 
    ); 

    return $args; 

} 
add_filter('woocommerce_shortcode_products_query', 'so_31541643_recent_products_shortcode_args', 10, 2); 

完全未经测试,在测试前不要使用在生产中。

+0

嗨 - 我很抱歉没有审查这个,我正在度假。我将它添加到了functions.php中,它完美的工作!非常感谢!优秀的代码和解释。 – WilliamAlexander

+0

@WilliamAlexander其中functions.php文件你添加到?到主网站或主题的? – davidrayowens

+0

@davidrayowens总是你的主题'function.php'。 – helgatheviking

相关问题