Mar 202010
 

Recently I installed the simple, but beautiful Suffusion theme by Sayontan Sinha. This theme is using the funtions.php file extensively, the same place where my shortcode definitions were stored. Sayontan will probably fix this in the near future by including a custom functions.php file from another location. I also used some PHP code in two sidebar widgets that was executed by the Exec-PHP plugin.

I thought, why not use a plugin to define shortcodes and execute PHP code snippets? I couldn’t find one, so I wrote one myself. You can find it in the WordPress repository as Shortcode Exec PHP.

Example shortcode to print your age:

extract(shortcode_atts(array('birthdate' => 'Jan 1, 1980'), $atts));
return floor((time() - strtotime($birthdate)) / (60 * 60 * 24 * 365.2425));

If you named the shortcode age, you can execute it in pages, posts, comments, widgets and/or RSS feeds like this:

[age birthdate="Mar 20, 2010"]

Please, use the forum for questions, bug reports and feature requests.

If you know a nice shortcode, you can leave it in the forum too.

Install now

Listing posts

If you want to list posts or pages on a post, page or in a widget, you can use the code below.

// Prevent recursion
global $outerPost;
if ($outerPost)
	return '';
 
// Parse parameters
extract(shortcode_atts(array('query' => 'post_type=post'), $atts));
$query = html_entity_decode($query);
 
// Create new post loop
global $post;
$outerPost = $post;
$my_query = new WP_Query($query);
while ($my_query->have_posts()) {
	$my_query->the_post();
	setup_postdata($my_query->post);
 
	// Process post
	echo '<em>'; the_title(); echo '</em>';
	echo '<div style="font-size: xx-small; border: 1px solid;">';
	the_content();
	echo '<div>';
}
$post = $outerPost;
$outerPost = null;
setup_postdata($post);

Example usage:

[list_posts query="author_name=marcel"]

Look here for possible query parameters.
Be sure the shortcode option ‘Output echoed‘ is checked.

Using forms

Example of form handling:

if (isset($_POST['form_select']))
	echo 'You selected ' . $_POST['form_select'] . '<br />';
?>
<form method="post">
<select name="form_select">
<option selected="selected" value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<input type="submit" value="Submit" />
</form>

Be sure the shortcode option ‘Output echoed‘ is checked.

 Posted by at 16:11  Tagged with:

  600 Responses to “WordPress plugin: Shortcode Exec PHP”

  1. Support questions can be asked in this forum now.

  2. I need to pass variables from the query string into posts, form submits, etc.. for example… http://internetmarketingsuperfriends.com/get-a-free-episode/?src=google&kw=internet+marketing&subid=22&cid=44

    For some reason this is completely escaping me how to capture these vars from the query string??

    I am using Thesis & Themedy, have custom.php file with no mods.

    I have the shortcode “first” created, enabled, and output echoed, then also placed into the post here http://internetmarketingsuperfriends.com/2011/05/12/whats-up/?first=Mike

    thanks in advance for any guidance you can offer.

    - Mike

  3. Hi,

    Thanks for a great plugin which I use extensively in my games site.

    I’ve searched through the files but can’t find where the php code for each shortcode is stored.

    Please could you advise where the code is to put my mind at rest, I’d hate to attempt an update of some sort and lose it all, as I’m not a great coder and would never be able to recreate.

    Thanks
    Mark

    • You can use the export function to export all shortcodes definitions, including the code you have written. The shortcode definitions are stored as options and therefore not easily accessible.

  4. Hi,

    Can I use the code from addthis.com to display the social mediabar through your plugin?
    The code looks like this:

    var addthis_product = ’wpp-262;
    var addthis_config = {”data_track_clickback”:true,”data_track_addressbar”:false};if (typeof(addthis_share) == ”undefined”){ addthis_share = [];}

    Thanks,
    Dennis

  5. Hi, Thanks for the great plugin!

    I am, however having an odd issue. when using Date (“D”) through the plugin it is retrieving the first three letters of the next day as opposed to the current day. e.g. http://jasonpitts.com/learn-php-switch-statement/
    I thought this might be a server time issue, but when I use the code in its own .php file http://jasonpitts.com/dev/netbeansprojects/jp_tutorials/learn_php_switch_statement.php it retrieves the current day. Do you know what could be causing this error? thank you!

  6. I want to setup this code. How to convert it to your plugin completely? It ‘ll be helpful if you can make this example.

    My example: it ‘ll show posts from luxury class on a category with best ranking.

    have_posts()) : $luxuryclass->the_post(); ?>
    <a href=""><img src="" alt="" />
    <a href=""><img src="/images/star.png" alt="Hotel Category" class="category" />

    • Part of your example was ‘eaten’ by the filters of WordPress (next time use code or pre tags). It seems like you can use the example ‘Listing posts‘ above with some modifications.

  7. is it not possible to use 2 more more short codes on one page?

    im receiving the following error when trying to run a script to display the results of 7 separate mysql tables on a single page:

    Fatal error: Cannot redeclare display_db_query() (previously declared in /home/content/15/6038315/html/wp-content/plugins/shortcode-exec-php/shortcode-exec-php-class.php(918) : eval()'d code:7) in /home/content/15/6038315/html/wp-content/plugins/shortcode-exec-php/shortcode-exec-php-class.php(918) : eval()'d code on line 44

    • You can execute as many shortcodes on one page as you like. The problem you have is that you redeclare a function in one or more shortcodes name ‘display_db_query‘.

      Solution: use something like:

      if (!function_exists('display_db_query')) {
      	function display_db_query() {
      	}
      }
  8. How do I use this? There’s 2 boxes to put PHP into – one with Save/Test/Revert/Delete buttons under it, one just with an Add button under it. Where do I put my code?

    If I paste in your code above for list_posts, all I get is “Are you sure you want to do this?” when I click “Add”. Nothing happens (in Chrome) if I click the Test button, even if I leave the default hello_world in there – no page change, no result, nothing. WP is 3.2.1

    • The box with Save/Test/Revert/Delete below it is for an existing shortcode, the box with Add below it for a new shortcode. You will get a new, empty box if you press Add (if everything is filled in correctly). So, there will be one box more as the number of shortcodes you have defined.

      If you press Test, you should have a spinning wheel next to the button for a moment and after that a popup with the result of the shortcode.

  9. To use Dynamic Content Gallery I need to put

    in my template file. I did & it worked fine. I figured it would be easier to do it if I used your plug in, so I associated that line w/ a shortcode but got a parse error

    Parse error: syntax error, unexpected '<' in /home/pleases0/public_html/wp-content/plugins/shortcode-exec-php/shortcode-exec-php-class.php(947) : eval()'d code on line 1

    Is there an easy way to fix this?

  10. Moving my test environment to the host, and installing shortcode exec php, when I try to activate I get Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /usr/local/pem/vhosts/150805/webspace/siteapps/159859/htdocs/wp-content/plugins/shortcode-exec-php/shortcode-exec-php-class.php on line 70

    Could you help? Thanks!

    • This error is probably caused by a PHP 4 incompatibility that was introduced in version 1.34 with the new import/export function. Could you please install the development version (follow the link in the changelog) and let me know if this problem is solved? Don’t worry, the development version is tested and the change is small.

      • Trying to upload, I get:
        Warning: unlink(): No such file or directory in /usr/local/pem/vhosts/150805/webspace/siteapps/159859/htdocs/wp-admin/uploader/upload.php on line 30
        Can't unpack zip-file: PCLZIP_ERR_MISSING_FILE (-4) : Missing archive file ''

        Argh!

        What consequences could result from upgrading to php5?

        • You can try to upload the file again. Also check if the download was successful. Maybe the file is not complete.

          You can also try to unpack the file and transfer the contents using FTP to the folder

          .../wp-content/plugins/shortcode-exec-php/...

          I would like to know if it fixes your problem, before you upgrade to PHP 5.

          WordPress does run well on PHP5 and most plugins too (some do even require PHP5, like some of mine), but it is better to check beforehand if everything runs fine on PHP5. WordPress will require PHP5 in the near future, so you will have to upgrade to PHP5 anyway. Switching to PHP5 is documented in the WordPress codex.

          Some hosting providers let you choose the PHP version using the hosting control panel. If you can, then you could switch to PHP5, check if everything runs fine and if not switch back to PHP4.

          • I suspected the hosting service (mydomain.com) was doing something wierd with permissions (I asked them repeatedly to fix it but they didn’t) so I signed up for a free 2 week trial with dreamhost (has anyone ever heard of them?). Now the shortcode and events calendar work.
            http://www.innisardenorg.dreamhosters.com

  11. I am running the latest version of the plugin, which supports Version 3.3 of WordPress, but in WP 3.3-beta3, the plugin’s Tools page rarely shows the line number and syntax highlighting for each shortcode’s source code. Instead it is normally displayed in a proportionally spaced font.

    In case it is relevant, I am running on the second site of a MultiSite (“Network”) installation of WordPress.

    As I’ve said before, I really rely on this great plugin!

    • That’s odd. I have been using the plugin on WordPress 3.3 beta 3 myself without any problems so far.

      Could you please try if you have this problem in another browser (Chrome, Firefox, etc) too?

      The editor should work on a network install the same.

      • My original comment was based on my use of FireFox 6.0.1. I get the same results on IE 9.0.3. I have the latest version of Java, Version 6 Update 29.

        I have WP-Table Reloaded 1.9.2 activated in this second site. Contact Form 7 3.0.1 is activated on the first site, but not the second. No other plugins are installed.

        Let me know what else I can provide that might help.

        • I would like to see this problem for myself. Please contact me through the contact form if you are willing to allow me to take look at your WordPress backend.

        • This problem should be fixed in the today released version 1.35.
          Please let me know if this is not the case.

          • The new version fixes this problem. Thank you, as always, for such great support!

  12. Hi, I need to validate if empty the field question in my form, how I can do it ?

    Votre adresse courriel :

    Votre nom :

    Votre prénom :

     

    • In principle this is possible using a shortcode, but you will have to understand how everything fits together. The shortcode should output not only the form, but also some JavaScript (assuming you want to check in the browser for empty fields). Take for example a look here for more information on how this works or search for “html form validate” with your favorite search engine to find more website explaining this.

  13. Is it possible to use a Exec PHP shortcode to output an if statement? EG:
    if($x == $y)
    And in the PHP page have
    [shortcodename] Content which only displayed if statement is true [/shortcodename]

  14. I am building a large site using over 100 Shortcode Exec PHP supported shortcodes.

    Shortcode Exec PHP appears to work more reliably on my site if I use underscores rather than hyphens in names of the shortcodes: [book_copyright_year] rather than [book-copyright-year].

    Thanks for a great tool.

  15. Shortcode Exec PHP is a fantastic tool, but it has some hidden, built-in, limits on length of shortcode. It would help me a lot to know exactly what they are. Shortcodes greater than around 50 characters will fail to be saved. What is the exact limit? Two shortcodes with the same first 15 or 20 characters will save but will not work when called. What is that limit?

    Thanks so much for your plugin and your help.

    • The plugin itself and WordPress do not have practical limits.
      My best guess the limits are enforced by your hosting provider/server.
      Past the following into a shortcode definition and you will able to see most limits:

      phpinfo();
  16. I have been playing around with this plugin, it’s pretty cool. But i have a question is it possible to call functions from an external file using include ? if so where would be the best place to save the file in my wordpress folder? Thanks :)

    • The simplest place where you can define external functions is the functions.php file of your (child) theme. It is also possible to define functions in the shortcode definition itself or even to include an external file in a shortcode definition, although I don’t recommend this, because this is less straight forward.

      • Thanks Marcel, ill just define them in the functions.php that seems the easiest way. :)

  17. Hello,

    I like the plugin and thank you for your support.

    I would like to display the Title of the post in the same post like :

    I have tryed this:

    extract(shortcode_atts(array('arg' => 'default'), $atts));
    function ODD_title($char) {
    $title = get_the_title($post->ID);
    $title = substr($title,0,$char);
    echo $title;
    }

    but of course it does not work. I am new to php.

    It must be very simple to write the snippet for this. Thank you again !!

  18. Hello. Thanks for this useful plugin, but on another instance of wordpress i have a issue: I installed and activate the plugin and there is no option displayed in wordpress settings. I reactivated, problem still there. Can you help me with this, please?

    • Does the logged in WordPress user havr ‘manage_options‘ capability?
      (normally administrators only)

      In the case of a network installation of WordPress: if you network activated the plugin, only the network administrator can access the settings (users with ‘manage_network‘ capability).

      • Yes, i’m logged in with administrator user.
        First i used WordPress dashboard to install the plugin. I deactivated, deleted and reinstaled manually. I logged off, retry… no result.
        I’m using WordPress 3.2.1 and the latest version of plugin. A friend of mine claims that this happened to him but after closing the browser and logged in, in settings option is displayed.
        Thanks alot for your help.

  19. How might we use shortcodes in the Header?

    • There is only one way, with this code in your theme:

      < ?php echo do_shortcode('[the_shortcode]'); ?>

      WordPress does only process shortcodes by default in posts and pages. The plugin offers a few options to process shortcodes at other places, like in widgets, but processing shortcodes in the header can only be done by modifying your theme.