首页 > 解决方案 > 在 WooCommerce 产品自定义选项卡中添加来自特定 ID 的产品

问题描述

我正在使用基于将自定义多选字段添加到 Woocommerce 中的管理产品选项设置生成的代码

// Display a multiselect field in "Linked Products" section
add_action( 'woocommerce_product_options_related', 'display_handles_product_field' );
function display_handles_product_field() {
    global $product_object, $post;
    ?>
    <p class="form-field">
        <label for="handles_product"><?php _e( 'Handles Product', 'woocommerce' ); ?></label>
        <select class="wc-product-search" multiple="multiple" id="handles_product_ids" name="_handles_product_ids[]" data-placeholder="<?php esc_attr_e( 'Search for a product&hellip;', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products_and_variations" data-exclude="<?php echo intval( $post->ID ); ?>">
            <?php
                $product_ids = $product_object->get_meta( '_handles_product_ids' );

                foreach ( $product_ids as $product_id ) {
                    $product = wc_get_product( $product_id );
                    if ( is_object( $product ) ) {
                        echo '<option value="' . esc_attr( $product_id ) . '"' . selected( true, true, false ) . '>' . wp_kses_post( $product->get_formatted_name() ) . '</option>';
                    }
                }
            ?>
        </select>
    </p>
    <?php
}

// Save the values to the product
add_action( 'woocommerce_admin_process_product_object', 'save_handles_product_field_value', 10, 1 );
function save_handles_product_field_value( $product ){
    $data = isset( $_POST['_handles_product_ids'] ) ? array_map( 'intval', (array) $_POST['_handles_product_ids'] ) : array();
    $product->update_meta_data( '_handles_product_ids', $data );
}

此代码在创建或编辑产品时添加自定义搜索框并在管理区域中添加相关产品。

我还在产品页面上创建了一个新选项卡来显示添加的产品。

/* New Handles Product Tab */
add_filter( 'woocommerce_product_tabs', 'new_handles_product_tab' );
function new_handles_product_tab( $tabs ) {
    
    /* Add new tab */
    $tabs['new_handles_product_tab'] = array(
        'title'     => __( 'Handles Product', 'woocommerce' ),
        'priority'  => 50,
        'callback'  => 'new_handles_product_tab_content'
    );

    return $tabs;

}

/* Display content in new tab */
function new_handles_product_tab_content() {
    
    // Content

}

告诉我如何正确地将这些产品添加到新标签中?我的代码正确吗?

我会很高兴你的帮助!

标签: phpwordpresswoocommerceproductshortcode

解决方案


使用[products]ids参数的简码,在自定义产品选项卡中显示产品句柄的函数将是:

function new_handles_product_tab_content() {
    global $product;
    
    $product_ids = $product->get_meta( '_handles_product_ids' ); // Get handles
    
    if( ! empty($product_ids) )
        $product_ids = implode(',', $product_ids);
        
        echo do_shortcode( "[products ids='$product_ids']" ); // Using [products] shortcode for display.
}

未经测试它应该工作。


推荐阅读