php - 在 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…', '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
}
告诉我如何正确地将这些产品添加到新标签中?我的代码正确吗?
我会很高兴你的帮助!
解决方案
使用[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.
}
未经测试它应该工作。
推荐阅读
- java - 将二维数组拆分为多个部分
- azure-devops - 修复 RunUAT.bat
- django - Django 和 PosgresSQL 在每次保存时添加一个时区偏移量
- python - 在 Pandas 中合并两个数据框将在合并结果中创建所有两个数据框列
- github - 限制 Github 组织分叉
- ios - 使用索引访问数组元素时出现错误“在展开可选值时意外发现 nil”
- php - 如果值为空 ("") 或 (null),则从嵌套/多维数组中删除键
- python - 从 keras.engine 导入 InputSpec 停止工作
- nuxtjs - 如何停止输入类型数字字段的nuxtjs轮/滚动事件?
- sql - 如何忽略子查询中的空值?