2017-07-15 181 views
1

我已將一個自定義按鈕添加到與產品meta demo_url相關聯的產品頁面,該頁面只是由每個產品更改的URL(爲每個產品打開實時演示分別在一個燈箱中)。代碼很簡單:僅在某些類別的WooCommerce產品頁面上顯示自定義按鈕

function my_extra_button_on_product_page() { 
    global $product; 
    $demo_url = get_post_meta(get_the_ID(), 'demo_url', true); 
    echo '<a class="fancybox iframe" data-width="1280" data-height="720" href="'.$demo_url.'"><button style="background: lightblue; padding-left: 19px; padding-right: 19px;">Przymierz</button></a>'; 
} 

事情是,店裏有一些其他產品不使用現場演示功能。它們被列在不同的類別中。我希望此按鈕僅在某些產品類別中可見(或者對於兩種產品類別不可見 - 任何更簡單的情況)。

我想這應該通過get_cat_ID($ cat_name)完成,但我不確定如何編寫if函數,並且通常我在編碼方面經驗不足。也許這樣的事情可以工作?

if get_cat_ID($cat_name) = categoryname { 
    echo 'button code'; 
else 
    echo 'no button code'; 
endif 
} 

我該如何讓它工作?

感謝

回答

0

你可以用下面的掛鉤函數實現它,在它定義所有你需要的產品類別:

add_action('woocommerce_single_product_summary', 'custom_button_by_categories', 32 ,0); 
function custom_button_by_categories(){ 

    global $product; 

    // Define your categories in this array (can be Ids, slugs or names) 
    $product_cats = array('clothing', 'music', 'furnitures'); 

    if(has_term($product_cats, 'product_cat', $product->get_id())){ 
     $demo_url = get_post_meta($product->get_id(), 'demo_url', true); 
     echo '<a class="fancybox iframe" data-width="1280" data-height="720" href="'.$demo_url.'"><button style="background: lightblue; padding-left: 19px; padding-right: 19px;">Przymierz</button></a>'; 
    } 
} 

代碼放在您的活動子主題的function.php文件(或主題)還是在任何插件文件中。

該按鈕將爲您定義的類別出現波紋管addtocart按鈕。您不需要自定義任何模板。

如果你想解除對上述類別添加到購物車按鈕(僅保留您的自定義按鈕,可以在條件中加入這一行:

remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30, 0); 

所有的代碼進行測試,並在WooCommerce工作版本3+

相關問題