将自定义字段外部 link 添加到存档类别页面

Adding a custom field external link to archives category pages

我有一个 woocommerce 网站。首先,我想在管理产品页面上添加一个自定义字段,以设置我将在我的档案类别产品页面上使用的 exernal url

我还希望在我的管理产品页面设置元框中有这个自定义字段。但是我更改了所有档案页面上的 link 的代码。

目前我的代码没有满足我的需要:

remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
add_action( 'woocommerce_before_shop_loop_item', 'mycode_woocommerce_template_loop_product_link_open', 20 );
function mycode_woocommerce_template_loop_product_link_open() {

    $url = 'https://www.some_domain.com/';

    echo '<a href="' . $url . '">';

}

我怎样才能让它只在类别档案页面上工作?

谢谢

第 1 步 - 在管理产品页面设置 metabox 中创建自定义字段:

// 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 步 - 仅在产品类别存档页面中用自定义元值替换 ​​link。

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 文件或任何插件文件中。

此代码已经过测试并且有效