user1738483 user1738483 - 1 year ago 84
PHP Question

Adding a custom field external link to archives category pages

I have a woocommerce web site. First I would like to add a custom field on admin product pages to set an exernal url that I will use on my Archives category product pages.

Also I would like ideally to have this custom field on my admin product pages settings metabox. But the code I have change the link on all archives pages.

For now I have this code that is not doing what I need:

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 = '';

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


How can I do to make it work on category archives pages only?


Answer Source

Step1 - Creation of a custom field in the admin product pages setting metabox:

enter image description here

// 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 ) );

Step 2 - Replacing the link by a custom meta value in product category archives pages only.

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">';

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested annd works