4

The format for the shortcode that I wish to do is: [product id="id#"] The format for do_shortcode is: do_shortcode('[shortcode');

My question is how can I insert a PHP variable as the id#?

I have a variable $itemid that I would like to use like this:

echo do_shortcode('[product id="$itemid"])

But I cannot for the life of me get it to work. Any suggestions would be greatly appreciated.

Lucas Mercer
  • 69
  • 1
  • 1
  • 5

3 Answers3

10

This is an issue of single quotes vs double quotes,

see What is the difference between single-quoted and double-quoted strings in PHP?

this fix should work:

echo do_shortcode("[product id=\"$itemid\"]")
Community
  • 1
  • 1
Uri Goren
  • 13,386
  • 6
  • 58
  • 110
9

Try this

$short = '[product id="'.$itemid.'"]';
echo do_shortcode($short);  
Dev Danidhariya
  • 683
  • 6
  • 16
2

Create your custom shortcode using add_shortcode function,

function products($id) {
    print_r($id);
}
add_shortcode( 'product', 'products' );


$itemid = "132";

concatenate the $itemid in do_shortcode function like below

echo do_shortcode('[product id="'.$itemid.'"]');

Output

Array ( [id] => 132 )
Noman
  • 4,088
  • 1
  • 21
  • 36