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. I’m developing a wordpress site on the local host. I would like the blogroll to be a dropdown menu. “Drake” on the Aquoid Forum (Suffusion) suggested your plugin so I downloaded and activated. Is there supposed to be an administration panel for the plugin?

    I’ve dragged the widget to my sidebar. I found some code that should do the trick at http://www.cybercoded.net/wp-content/uploads/2009/01/blogrollpulldown.txt :

    function dropdown_links(){
    global $wpdb;
    $sql = "SELECT link_url, link_name, link_description FROM $wpdb->links WHERE link_visible = 'Y' Order By link_name";
    $results = $wpdb->get_results($sql);
     
    if (!$results) {
    	return; }
     
    $output ='
     
    Select ... ';	
    foreach ($results as $row) {
    	$the_link = '#';
    	if (!empty($row->link_url)){
    		$the_link = wp_specialchars($row->link_url);
    	}
     
    	$desc = wp_specialchars($row->link_description, ENT_QUOTES);
    	$name = wp_specialchars($row->link_name, ENT_QUOTES);
    	$title = $desc;
     
    	if ('' != $title) {
    		$title = ' title="' . $title . '"';
    	}
     
    	$alt = ' alt="' . $name . '"';
     
    	$output .= ''.$name.'';		
    }
    	$output .= '';		
    	echo $output;
    }

    I added function ‘dropdown_links’ to functions.php. I tried calling it several ways in the text widget:

    and
    ?> php dropdown_links(); [ dropdown_links(); ] <? and
    [ dropdown_links(); ] and
    dropdown_links();

    Clearly I'm an amateur but trying! Any help would be much appreciated!

    • Try this:

      Select ‘Shortcode Exec PHP‘ from the WordPress ‘Tools menu‘.

      Enable the option ‘Execute shortcodes in (sidebar) widgets‘.

      Scroll a little bit down and create a new shortcode, name it for example ‘dropdown_links‘ and put this code into the editor:

      global $wpdb;
      $sql = "SELECT link_url, link_name, link_description FROM $wpdb->links WHERE link_visible = 'Y' Order By link_name";
      $results = $wpdb->get_results($sql);
      if (!$results)
      	return;
       
      $output ='<form action="" name="dd">
      <select name="dd2" onchange="document.location=dd.dd2.options[selectedIndex].value">
      <option value="">Select ... </option>';
      foreach ($results as $row) {
      	if (empty($row->link_url))
      		$the_link = '#';
      	else
      		$the_link = esc_html($row->link_url);
       
      	$desc = esc_html($row->link_description);
      	$name = esc_html($row->link_name);
      	$title = $desc;
       
      	if ($title != '')
      		$title = ' title="' . $title . '"';
       
      	$alt = ' alt="' . $name . '"';
       
      	$output .= '<option value="' . $the_link . '">' . $name . '</option>';
      }
      $output .= '</select></form>';
      echo $output;

      Don’t forget to save the shortcode.

      Now add a text widget and put this into it: [dropdown_links]

    • If you want to lean about shortcodes, start reading here.

  2. Hi Marcel

    Any way around to use your excellent plugin in custom fields ?

    Awesome idea this plugin

    • The problem with custom fields (actually post meta data) is that it is custom. There is no way to know which values are available and how the value is being used. It is possible to use shortcodes in custom fields, if you manage to call

      do_shortcode();

      before the custom field value is being used (in your theme, backend, etc).

      Maybe I can give a more specific answer if you can be more specific about the custom fields involved (plugin? theme?).

  3. Thanks for the plugin. I have a client who needs to add some javacode snippets to pages from a form generating service and doing so in WordPress is challenging because if you switch to Visual mode from HTML mode after adding the script code, the script code is removed. So in comes your plugin.

    So first off thanks.

    My question please is this. As stated, I am not inserted PHP code and so having read your faq page, I inserted ?> … … <? around each code snippet, (which I suspect is there to simply close out the call to PHP code), but it did not do that. So I wondered what that was?

    The other options I did not understand was this one.

    Do not display code editor initially

    Thanks again.

    • What you did with the closing and opening tag should be correct.

      The option is to disable the rich editor when you go to the plugin page. This saves loading time, especially if you have a lot of shortcodes. Each editor can be switch to rich editor with a check box individually.

  4. Hi Marcel,

    As per your request, here is the code for a dropdown list of posts by category, that I want to make into a widget. Of course the question is how I configure the first few lines of the PHP to fit with you widget, or is it just “plug and play”, aka “paste and it works”.

    I removed the beginning and ending php tags.

    $cat_id = get_cat_ID('uncategorized');
    $args=array(
    'cat' => $cat_id,
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'caller_get_posts'=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
    ?>

    have_posts()) : $my_query->the_post(); ?>
    <option value="">

    <?
    wp_reset_query();

    • If you have the patience until I am back at home at the end of October, I will adapt the code to work with the plugin. I am traveling in a third world country currently, so I have very little resources (in fact only a small Android phone).

      • Sure Marcel, that would be great, and I think you should put such code snippets into an examples page that could be in the plugin, as some documentation. This is such a good plugin. I hope you develop the documentation. If I could learn more about the plugin, I can help to write some for you.

        • Documentation on PHP is available on a lot of websites. Documentation of WordPress can be found for example in the WordPress Codex and on a lot of websites specialized on WordPress development. The plugin can be used for a lot of things and is for the more advanced users or people that want to learn how to write PHP code in a simple way. I will help people to get their code working, but I will not write documentation, because that would just a repetition of what is already available.

          • Actually, I have a certification in PHP, CSS and a few other things. What is needed are some basic instructions on what your plugin requires, for example, we cannot start the PHP code snippet with <?php or it will break, so you do require specific things in this plugin to make the PHP code work, it is not “plug and play”, and the examples you give have some PHP code that is specific to your plugin.

            • There is no restricting to what PHP code can be executed. The only special requirement is that the PHP start and ending tags must be deleted (a requirement of the eval function). Also keep in mind that the PHP code is executed within a function within the WordPress environment. See the FAQ for some more information.

  5. Hi, I am trying to use Shortcode Exec PHP along with Advertising Manager (http://wordpress.org/extend/plugins/advertisement-management/)

    I add two of the same shortcode with different arguments into that plugin in “Below title inside post”, then I visit a post, and only the first shortcode gets converted, the other appears as clear text like [shortcode...args].

    Which part of the code should I look at for fixing this?

    • Using:

      [shortcode...args/]
      [shortcode...args/]

      Worked fine, I was closing it with [/shortcode] and that didn’t work.

  6. hey im trying to use php mysql to retreive some stuff from a data base, its a pretty simple code but for some reason when i add the shortcode to a page it screws up my menu and adds an error code:

    Warning: mysql_real_escape_string(): 14 is not a valid MySQL-Link resource in C:\HostingSpaces\tronic9t\tutorial-wizards.com\wordpress\wp-includes\wp-db.php on line 774

    • I have no idea what is causing this error. Try using the WordPress database functions instead of direct MySQL functions. It is safer and simpler. Don’t forget a global $wpdb;

  7. Great Plugin. However, I created my website on a localhost but when I uploaded it to an actual hosting site my shortcode scripts disappeared. Is there a way of exporting them so that they are move along with the rest of the site ??

    • There is no export function, yet. I already promised to make it to someone else. Currently I am traveling, so it will take some time (about a month).

      The shortcode definitions are stored in the database, so if you migrate the database, you will migrate the shortcodes too.

  8. Additional help.
    I am trying to create a piece of code that would pull in search results for a particular keyword into a page. I tried the listing Post code above and it works but i need it to only pull the Title and link to the page, it is currently pulling the whole story.

    I also need to know how to change this to search for a specific keyword and not all posts by a user:

    [list_posts query="author_name=marcel"]

    I am asking a lot i know but any help would be greatly appreciated.

    Thanks
    D

    • If you don’t want to display the post content, remove the line with ‘the_content’ and the line before and after it.

      Follow the link for the query parameters just below the code to find out if you can search for keywords.

      Normally I would help a little bit more, but I am traveling in a third world country until the end of october, so my resources are limited.

  9. I have installed this plugin and it seems to work fine. The problem i have is that i have no PHP skills so i dont know haw to change the following to work:

    I want it to pull in my comments feature into the page rather than have it in the wp template.

    Can anyone help.
    Thanks
    David.

  10. Excellent plugin. I’m using it to add image tags on my posts. [image name="file name"]
    It works great and I can see the images on my posts.
    But when the feed goes out to RSS readers, instead of seeing the images, I see the above shortcode displayed in text. Any thoughts?

  11. I put some PHP code in a shortcode editor box. A string in the code contains the HTML symbol for a non-breaking space. That symbol seems to break the editor. When I press Save it appears to save, but if I navigate away from the page and come back, all the code after the non-breaking space has been lost.

    This is valid PHP code, as it works if I put it in a separate PHP file. I can work around this now that I know about it, but you might want to look into it when you get a chance.

    Thanks for your very useful plugin.

    • Try enabling the plugin option ´Disable html entity encoding´. Editing HTML with HTML always has this side effect.

  12. Does this work with Multi-Sites? The settings page is only listed on the Network admin settings after network activating.

    Thanks

    • Yes, it works on multi-sites. If you network activated the plugin it will only be available on the network admin settings. This is the most secure way of activating. You can activate the plugin also as a ‘normal’ plugin, then it will be available on each site.

  13. I am trying to use your plugin – and it works great!!! Almost.

    I have people posting blogs with some generated text which includes [shortcode]. I am trying to replace [shortcode] with an image. It works great in the post/page itself, however it does NOT work when being fetched by a widget as an excerpt.

    It used to say – [shortcode] lorem ipsum dolor sit, blah blah [read more...]

    Now it just says – lorem ipsum dolor sit, blah blah [read more...]

    I have all the options enabled, including execute in excerpts. :/

    • Your theme is probably not behaving as it should. Try switching to the default theme (Twenty Ten or Eleven) temporarily to see if this is the case.

  14. I’m trying to use a short code in my menu (traditional twentyeleven) and placed the shortcode in the navigation title but it doesn’t appear to work. Is there a checkbox in the settings I need to have clicked in order for that to work?

    • There is no option to make shortcodes work in titles.
      You can try to add this to your functions.php in the theme folder:

      add_filter('the_title', 'do_shortcode');
  15. Hi there,

    Nice plugin! Would be awesome to be able to export all code!

    Regards, Antoon

  16. Great plugin!

    Feature request: Extend this plugin so that in addition to adding short codes, one can add actions and filters. That would provide a quick and easy way to hook callbacks into WP without having to write a new plugin and install it.

    • Shortcodes and actions/filters are something completely different. Actions and filters belong in functions.php or better in a separate plugin IMHO.

  17. Hallo,
    it’s a very very nice plugin.
    Only one thing… is it possible to insert code like this?
    require("function.php");
    thank you for your answer,
    Antonio

    • Yes, that is possible.

      • Hy Marcel, thank you for you timely answer but i tried to insert include("http://pendolari.org/tranitalia/function.php"); and seems that something wrong because i get this error:

        Warning: require() [function.require]: URL file-access is disabled in the server configuration in /mounted-storage/home147/sub043/sc79739-KDJD/pendolari.org/wp-content/plugins/shortcode-exec-php/shortcode-exec-php-class.php(893) : eval()'d code on line 1

        Warning: require(http://pendolari.org/trenitalia/function.php) [function.require]: failed to open stream: no suitable wrapper could be found in /mounted-storage/home147/sub043/sc79739-KDJD/pendolari.org/wp-content/plugins/shortcode-exec-php/shortcode-exec-php-class.php(893) : eval()'d code on line 1

        Fatal error: require() [function.require]: Failed opening required 'http://pendolari.org/trenitalia/function.php' (include_path='.:/usr/share/php5/') in /mounted-storage/home147/sub043/sc79739-KDJD/pendolari.org/wp-content/plugins/shortcode-exec-php/shortcode-exec-php-class.php(893) : eval()'d code on line 1

        Can you help me please?

        • Your question before is a little bit different from what you are doing. Including a local file is different from including a remote file. The latter is most often blocked by your hosting provider for security reasons.

      • Sorry Marcel, my english is really bad and i don’t explain so well the problem.
        shortcode-exec plugin is installed on http://pendolari.org wordpress blog. I need to include function.php and it’s loaded in “http://pendolari.org/trenitalia” folder but in this way i get error descripted above.

        You can see your plugin working
        here: http://pendolari.org/monitoraggio-treni/ (error)
        and here: http://pendolari.org/monitoraggio/ at this link, relative data field, should be javascript calendar but using this code

        the calendar doesn’t work.
        I hope that my english is just little understandable

        • Try using a server path instead of an URL. Most often the FTP path is the same. Also, including functions.php in the theme folder is done automatically by WordPress.

  18. Beste Marcel,

    Ik liep tegen je plugin aan op zoek naar een shortcode waarmee ik in een pagina een specifiek bericht kan openen.

    Als ik het goed begrepen heb, kan ik dat met jouw voorbeeldscript (van [list_posts query="author_name=marcel"]) voor elkaar krijgen door de shortcode [list_posts query="p=115"] in mijn bericht te typen, correct?

    Ik heb geen idee wat er misgaat, maar ik krijg het niet voor elkaar. Hij doet het niet. Ik heb de code van deze pagina geknipt/geplakt naar de plugin, dus typfouten kunnen er niet in zitten. Als jij je licht erover zou kunnen laten schijnen, dan graag,

    Misschien moet ik iets aanzetten in de plugin opties?

    Vast hartelijk dank,
    Jandra

    • Edit: Hij toont in de pagina gewoon de tekst van de shortcode i.p.v. hem uit te voeren.

    • Page or post? Normally shortcodes should be executed on both.Try switching to the default theme to find out if your theme is preventing the shortcode from executing. It is also possible, although rare, that another plugin is conflicting.

  19. Hello : )

    See below code (one of many similar) that I am trying to execute inside a WP Page so I loaded it into your plugin window “as is” after naming it then went to the tinymce panel to select and insert the shortcode, but script does not execute. I get a syntax error. (not a php programmer, just got this code from popshops to plug into my page); realize I can paste inside page.php and maybe get it to work, but then I will have many pages. What to do; will your shortcodesexec work for me? Thank you, SandraL

     $value) {
                  if (strpos($key,"psps_") > -1 ) {
                    $psps_parameters .= '&'.$key.'='.urlencode($value);
                    $psps_base_url = str_replace('&'.$key.'='.urlencode($value), "", $psps_base_url);
                    $psps_base_url = str_replace($key.'='.urlencode($value), "", $psps_base_url);
                  }
                }  
     
                $psps_parameters .= "&psps_show_search=true";
                $psps_parameters .= "&psps_show_navigation=true";
                $psps_parameters .= "&psps_show_products=true";
     
                $psps_url = "?psps_base_url=".urlencode($psps_base_url);
     
                $psps_url="http://shops.popshops.com/shops/php/517d4g8sviz3b6bx1r7rn6idb$psps_url$psps_parameters";
     
                # Include the shop
                if (function_exists('curl_init')) {
                $shop=curl_init();
                curl_setopt($shop,CURLOPT_URL,$psps_url);
                curl_exec($shop);
                curl_close($shop);
                  } else {
                    readfile($psps_url);
                  }
                ?>
    • Sorry for the late response, I didn’t get a notify for it.
      Your script is incomplete (start is missing) and you shouldn’t include ?> at the end.

  20. Is it possible to define multi argument codes?

    • Oh wait, looks like this works:

      extract(shortcode_atts(array('arg1' => 'Yes','arg2' => 'No'), $atts));