I’m using the Cart66 WordPress plugin, and I’m trying to include a variable in a shortcode, you can see the code below:
$price = do_shortcode('[add_to_cart item="test-item" showprice="only" text=""]').' test';
echo do_shortcode('[add_to_cart item="test-item" showprice="no" quantity="1" text="'.$price.'" ]');
I’ve done some googling, and apparently this is the right way to include variables in WordPress shortcodes, but this doesn’t seem to work for me, Cart66 just falls back and uses the default “Add to Cart” text instead of the text defined in the shortcode above.
Can anyone see where I’m going wrong here?
As you have googled to add text in the shortcode is correct but not fully correct.
You have used “do_shortcode()” function which is used to replace the shortcode functionality and display its functionality in frontend. But, if you want to add a parameter in a shortcode and make it working you need to change the shortcode functionality a bit.
You have to find shortcode in your files containing the shortcode’s functionality:
Find code something like below:
add_shortcode('add_to_cart','function_name');
function function_name($atts)
{
$atts //-- will be used to add parameters as you needed
}
You can use PHP’s Output Buffering control
PS:
do_shortcode()
does not natively echo the output; whatever is bound on that action may echo by itself as well, which is when you either (A) edit the plugin, or (B) use OB.I think there were some weird characters in the returend value that were causing issues, I used the Expression code below, and it seemed to solve my issue:
Needless to say this was a very … complicated solution. I ended up using some good old SQL by utilising WordPresses WPDB class. Turning about 7 lines of code into 2:
This is a much better solution, I wouldn’t recommend trying to use shortcodes for things they weren’t intended to be used for.
The âadd_shortcodeâ function does not allow you to use external variables. It operates with a local scope, so any variables declared INSIDE will be recognized, but any variables OUTSIDE will not be recognized. If you want to use an external variable you will need to use global.
Using global on your external variable will pull it within scope and allow you to use it within the add_shortcode function! 🙂