首页 文章

WooCommerce自定义ShortCodes

提问于
浏览
1

我正在尝试为WooCommerce创建自定义短代码,我希望在帖子末尾显示特定类别的特色产品 .

有一个标准的短代码:

[featured_products per_page="12" columns="4" orderby="date" order="desc"]

我想为此添加catagory,所以新的短代码将是:

[featured_category_products category="13" per_page="4" columns="4" orderby="date" order="desc"]

为了使它工作,为它创建一个函数是必要的,所以我找到了包含所有默认短代码的class-wc-shortcodes.php文件 .

我根据默认的特色产品添加了一个新功能:

public function featured_category_products( $atts ) {

    global $woocommerce_loop;

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

    $args = array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'ignore_sticky_posts'   => 1,
        'posts_per_page' => $per_page,
        'orderby' => $orderby,
        'order' => $order,
        'meta_query' => array(
            array(
                'key' => '_visibility',
                'value' => array('catalog', 'visible'),
                'compare' => 'IN'
            ),
            array(
                'key' => '_featured',
                'value' => 'yes'
            )
        ),
        'tax_query'             => array(
            array(
                'taxonomy'      => 'product_cat',
                'terms'         => array( esc_attr($category) ),
                'field'         => 'slug',
                'operator'      => 'IN'
            )
        )
    );

    ob_start();

    $products = new WP_Query( $args );

    $woocommerce_loop['columns'] = $columns;

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

        <?php woocommerce_product_loop_start(); ?>

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

                <?php woocommerce_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">' . ob_get_clean() . '</div>';
}

我添加了类别变量提取(并检查它是否有效)并添加了税务查询部分(从另一个根据类别显示产品的函数中找到它) . 所以我认为这应该有效,但当然不是 . 我没有得到任何结果也没有错误 .

有人知道如何让这个工作?

1 回答

  • 0

    如果您只查找一个产品类别,请使用 'terms' => $category . 或者您可以执行explode()将逗号分隔的字符串拆分为数组 .

    Wp Query : Taxonomy Parameters .


    其他说明:

    请勿触摸插件文件,您的更改将在下次更新时丢失 .

    add_shortcode( 'featured_category_product', 'featured_category_product_function' );
    

相关问题