CodonPL
CodonPL

Reputation: 39

Get WooCommerce attribute value (url) to use it as a href link

I have an attribute in WooCommerce: demo_url. Every product has it's own URL inserted there.

I have also added a button near ADD TO CART so the user can easily view the product on his head (glasses shop). Clicking this button will redirect the user to outside application. Every glasses will have a different link for clicking.

I have tried something like that:

echo '<a href="'.$demo_url.'" target="_blank">Text</a>';

But it is not working at all. I've tried it with different global variables (like $currentday) but to no available.

I desperately need this to work. Could You please help?

Thanks

Upvotes: 2

Views: 3350

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254483

Instead an using a product attribute you should use a custom field (a custom field in the product pages general settings tabs).

Here is that code:

// Create and display the custom field in product general setting tab
add_action( 'woocommerce_product_options_general_product_data', 'add_custom_field_general_product_fields' );
function add_custom_field_general_product_fields(){
    global $post;

    $value = get_post_meta( $post->ID, '_demo_url', true );

    if(empty($value))
        $value = '';

    echo '<div class="options_group">';

    woocommerce_wp_text_input( array(
        'id'          => 'demo_url',
        'label'       => __( 'Demo Url', 'woocommerce' ),
        'placeholder' => 'http://',
        'desc_tip'    => 'true',
        'description' => __( 'Enter the Demo  Url.', 'woocommerce' ),
        'value'       => $value
    ) );

    echo '</div>';
}

// Save the custom field
add_action( 'woocommerce_process_product_meta', 'save_custom_field_general_product_fields' );
function save_custom_field_general_product_fields( $post_id){

    // Text Field
    $demo_url = $_POST['demo_url'];
    if( !empty( $demo_url ) )
        update_post_meta( $post_id, '_demo_url', esc_attr( $demo_url ) );
}

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

This code is tested and works... Then you will get this:

enter image description here

Now you can add in your code:

// If you dont have the product id use this:
$global $product;
$product_id = $product->get_id();

// Getting your custom product demo URL
$demo_url = get_post_meta( $product_id, '_demo_url', true );

// Add it to your button:
echo '<a href="'.$demo_url.'" target="_blank">Text</a>';

Upvotes: 3

Related Questions