WooCommerce广告自定义按钮,在添加到每个产品的购物车后具有自定义链接

时间:2020-03-03 作者:Peter Lang

我在谷歌上搜索了很长时间才找到这个片段。

有没有办法转换前端显示按钮而不是完整链接的代码段?例如,“立即购买”。单击此按钮将在新的浏览器窗口中打开外部页面。按钮的css将来自基本主题。

// This function gets the value for the the custom fields from the database and adds it to the frontend output function
function wpse_add_custom_link_output() {
    $external_link = get_post_meta(get_the_ID(), \'_custom_product_text_field\', true);
    $html = \'<a href="\'.$external_link.\'" class="custom-button-class" target="_blank" title="\'.__(\'External product link\',\'woocommerce\').\'">\'.$external_link.\'</a>\';
    echo $html;
};
add_action( \'woocommerce_after_add_to_cart_button\', \'wpse_add_custom_link_output\', 10, 0 ); 
// This function creates the field in the backend
function wpse_add_custom_link_field(){
    global $woocommerce, $post;
    echo \'<div class="product_custom_field">\';
    // Custom Product Text Field
    woocommerce_wp_text_input(
        array(
            \'id\' => \'_custom_product_text_field\',
            \'placeholder\' => __(\'Paste product link here\', \'woocommerce\'),
            \'label\' => __(\'Custom product link\', \'woocommerce\'),
            \'desc_tip\' => \'true\'
        )
    );
    echo \'</div>\';
}
add_action(\'woocommerce_product_options_general_product_data\', \'wpse_add_custom_link_field\');
// this function saves the link/text field
function wpse_save_custom_link_field($post_id){
    // Custom Product Text Field
    $woocommerce_custom_product_text_field = $_POST[\'_custom_product_text_field\'];
    if (!empty($woocommerce_custom_product_text_field))
    update_post_meta($post_id, \'_custom_product_text_field\', 
    esc_attr($woocommerce_custom_product_text_field));
}
add_action(\'woocommerce_process_product_meta\', \'wpse_save_custom_link_field\');

1 个回复
SO网友:7uc1f3r

正如您在wpse_add_custom_link_output 回调函数,该函数回显$html 变量

因此,您可以简单地替换以下行

$html = \'<a href="\'.$external_link.\'" class="custom-button-class" target="_blank" title="\'.__(\'External product link\',\'woocommerce\').\'">\'.$external_link.\'</a>\';
比如

$html = \'<button type="button">BUY NOW</button>\';

相关推荐