【问题标题】:WooCommerce custom ShortCodesWooCommerce 自定义简码
【发布时间】:2023-03-05 05:43:01
【问题描述】:

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

有一个标准的简码:

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

我想为此添加类别,因此新的短代码将是:

[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>';
}

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

有人知道如何让它工作吗?

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    如果您只寻找一种产品类别,请使用'terms' =&gt; $category。或者您可以使用explode() 将逗号分隔的字符串拆分为一个数组。

    Wp Query : Taxonomy Parameters


    其他说明:

    不要触摸插件文件,您的更改将在下次更新中丢失。

    • 创建your own plugin

    • 将您创建的函数复制到其中。

    • Register the shortcode 使其可用(使用您的自定义函数作为回调):

      add_shortcode( 'featured_category_product', 'featured_category_product_function' );
      

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    相关资源
    最近更新 更多