Search code examples
phpwordpresswoocommerceshortcodeproduct

Dynamic argument value in Woocommerce product shortcode


Background: My site sell keytags of a variety of styles (inventory contains 750+) but tags can only be sold as groups of three because that is how the inventory arrives. To get customers to only have the option to buy the group of three we created product bundles or sets (a separate product that contains 3 of a style) and I'm attempting to present that using the wordpress product shortcode replacing the add to cart button for the single tag style. The single tags and the corresponding bundle have similar sku names with the difference being a k at the end of the sku of bundles.

Problem: Below is the code that I'm using to check to see if the product is a single tag and if it is i'm inserting the single product shortcode where the add to cart was. It will not display the shortcode on the product pages

function add_content_after_addtocart(){
    $current_product_id = get_the_ID();
    $product = wc_get_product( $current_product_id );
    $bundSku = $product->get_sku();
    $bundSku .= "k";

    if( $product->is_type('simple') ){
        echo do_shortcode('[product size="small" sku="{$bundSku}"]');
    }      
}

add_action('woocommerce_after_add_to_cart_button','add_content_after_addtocart');

Solution

  • Replace this line:

    echo do_shortcode('[product size="small" sku="{$bundSku}"]');
    

    By this one:

    echo do_shortcode("[product size='small' sku='{$bundSku}']");
    

    It should work now… So your functional code will be:

    add_action('woocommerce_after_add_to_cart_button','add_content_after_addtocart');
    function add_content_after_addtocart() {
        $current_product_id = get_the_ID();
        $product = wc_get_product( $current_product_id );
        $bundSku = $product->get_sku();
        $bundSku .= "k";
    
        if ($product->is_type('simple')) {
            echo do_shortcode("[product size='small' sku='{$bundSku}']");
        }      
    }
    

    Code goes in function.php file of your active child theme (or theme). Tested and works.