• Resolved davidzohar

    (@davidzohar)


    Hi,

    i’m trying to have custom shortcode nested in a plugin shortcode.
    i learned that there is some limitation to WP shortcodes and to over come it I need to us the do_shortcode function

    i used this in my function file
    $childrens = do_shortcode(‘[products ids=”$string”]’);
    based on some research I tried:
    $childrens = do_shortcode(‘[products ids=”.’$string’.”]’);
    and this
    $childrens = do_shortcode(‘[products ids=\’$string’\]’);
    with no success.

    in my custom template i can see the correct output for the $string variable using echo $string results in “41,402” so i know it works ok

    when i use
    $childrens = do_shortcode(‘[products ids=”41,402″]’);
    i can see the desired behavior rendered on the page
    when i use
    $childrens = do_shortcode(‘[products ids=”$string”]’);
    i get all the results for the [products} shortcode as it ignore the $string variable.

    any thoughts?

    David

    The page I need help with: [log in to see the link]

Viewing 2 replies - 1 through 2 (of 2 total)
  • The shortcode inside do_shortcode() is a String, so needs to be wrapped in ' or ".

    To output a variable inside a string, you need to close the ' quote marks, use . to append to the string, then put the variable, before opening the string again and completing the shortcode:

    $childrens = do_shortcode( '[products ids="'. $string . '"]' );
    

    It’s also possible to just put a variable string if you use double quotes:

    $string = "This is $variable";
    

    But since shortcodes already contain double quotes you would need to escape them with \:

    $childrens = do_shortcode( "[products ids=\"$string\"]" );
    

    Another option is to use sprintf(), which can be used to substitute a placeholder in a string with a variable:

    $childrens = do_shortcode( sprintf( '[products ids="%s"]', $string ) );
    
    • This reply was modified 6 years, 10 months ago by Jacob Peattie.
    Thread Starter davidzohar

    (@davidzohar)

    Hi Jacob,

    Thank you so much!!!
    this solved the issue i had.

    David

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘using a variable inside do_shortcode()’ is closed to new replies.