PHP within a WordPress shortcode

I’ve got a PHP shortcode for WordPress, let’s call it [myshortcode].

The shortcode allows you to enter a download URL like this [myshortcode download=”http://www.example.com/file.pdf”].

Read More

I want to use this shortcode in a template file, but have the download url be a variable. Is this possible, and if so, how do I do it?

I tried these, but it doesn’t work…

<?php echo do_shortcode('[myshortcode download="<?php echo $variable['dllink']; ?>"]'); ?>
<?php echo do_shortcode('[myshortcode download="echo $variable['dllink'];"]'); ?>

Any ideas?

Related posts

Leave a Reply

2 comments

  1. <?php echo do_shortcode('[myshortcode download="'.$variable['dllink'].'"]'); ?>
    <?php echo do_shortcode("[myshortcode download="{$variable['dllink']}"]"); ?>
    

    I suggest you read this properly to understand why those work and yours didn’t 😉

  2. I think it depends on where the variable is defined. For instance, if the shortcode is part of a plugin that allows the admin to set some options on a settings page, then you would want php to retrieve those options and echo the value into the shortcode.

    Another way to do it would be to use a form with a $_POST method to submit a value to a table in the database, and then to call that value and set it to the variable.

    In a recent plugin I wrote (Recent Post Views), I included a shortcode which retrieved options from the database and inserted those as variables:

    //Get options from the settings page
    $options = get_option('cb_rpv_options');
    $select_bold = $options['select_bold'];
    $select_italics = $options['select_italics'];
    $select_list_style = $options['select_list_style'];
    

    These variables changed the output of the shortcode, which is what you’re trying to do. The best thing to do may be to download a plugin with well commented code as an example and build off that.

    I hope this is helpful, and I agree with the other post that you need to clean up your syntax too.