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

时间:2017-07-10 09:58:21

标签: php wordpress woocommerce attributes product

我在WooCommerce中有一个属性:demo_url。每个产品都有自己的URL插入。

我还在ADD TO CART附近添加了一个按钮,这样用户就可以轻松地在他的头上观看产品(眼镜店)。单击此按钮会将用户重定向到外部应用程序。每个眼镜都有不同的点击链接。

我尝试过类似的东西:

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

但它根本不起作用。我已尝试使用不同的全局变量(如$currentday),但没有可用。

我迫切需要这个工作。你能帮忙吗?

由于

1 个答案:

答案 0 :(得分:3)

相反,使用产品属性应使用自定义字段(产品页面常规设置选项卡中的自定​​义字段)。

以下是代码:

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

代码包含您活动子主题(或主题)的任何php文件或任何插件php文件。

此代码已经过测试并且有效......然后你会得到这个:

enter image description here

现在您可以添加代码:

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