Adding a custom field external link to archives category pages

前端 未结 1 1318
余生分开走
余生分开走 2021-01-14 16:32

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

1条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-14 16:42

    Step1 - Creation of a custom field in the admin product pages setting 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 '
    '; woocommerce_wp_text_input( array( 'type' => 'text', 'id' => 'extern_link', 'label' => __( 'External Link', 'woocommerce' ), 'placeholder' => '', 'description' => __( 'Insert url', 'woocommerce' ), ) ); echo '
    '; } // 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 '';
        //For the other woocommerce archives pages
        } else {
            echo '';
        }
    }
    

    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

    0 讨论(0)
提交回复
热议问题