第 1 步 - 在管理产品页面设置元框中创建自定义字段:
// Inserting a Custom Admin Field
add_action( 'woocommerce_product_options_general_product_data', 'add_custom_text_field_create' );
function add_custom_text_field_create() {
echo '<div class="options_group">';
woocommerce_wp_text_input( array(
'type' => 'text',
'id' => 'extern_link',
'label' => __( 'External Link', 'woocommerce' ),
'placeholder' => '',
'description' => __( 'Insert url', 'woocommerce' ),
) );
echo '</div>';
}
// Saving the field value when submitted
add_action( 'woocommerce_process_product_meta', 'add_custom_field_text_save' );
function add_custom_field_text_save( $post_id ){
$wc_field = $_POST['extern_link'];
if( !empty( $wc_field ) )
update_post_meta( $post_id, 'extern_link', esc_attr( $wc_field ) );
}
第 2 步 - 仅在产品类别存档页面中将链接替换为自定义元值。
remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open');
add_action( 'woocommerce_before_shop_loop_item', 'custom_wc_template_loop_product_link_open', 10 );
function custom_wc_template_loop_product_link_open() {
// For product category archives pages only.
if (is_product_category()) {
// You get here your custom link
$link = get_post_meta(get_the_ID(), 'extern_link', true);
echo '<a href="' . $link . '" class="woocommerce-LoopProduct-link">';
//For the other woocommerce archives pages
} else {
echo '<a href="' . get_the_permalink() . '" class="woocommerce-LoopProduct-link">';
}
}
代码位于您的活动子主题(或主题)的 function.php 文件中或任何插件文件中。
此代码已经过测试并且可以工作