简体   繁体   English

获取WooCommerce属性值(URL)以将其用作href链接

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

I have an attribute in WooCommerce: demo_url. 我在WooCommerce中有一个属性:demo_url。 Every product has it's own URL inserted there. 每个产品都在其中插入了自己的URL。

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. 我已经尝试了不同的全局变量(例如$currentday ),但是没有。

I desperately need this to work. 我迫切需要这个工作。 Could You please help? 能否请你帮忙?

Thanks 谢谢

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. 代码会出现在您活动的子主题(或主题)的任何php文件中,也可能出现在任何插件的php文件中。

This code is tested and works... Then you will get this: 此代码已经过测试并且可以工作...然后您将获得以下代码:

在此处输入图片说明

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM