WordPress shortcode with separate template/file?

I’m at an early stage of learning WordPress (and shortcode), so bear with me:

To me, shortcodes seem like a swiss army knife of not having to use page-specific templates for everything. I like to build as many pages in the wysiwyg as possible, but often I would need some (reusable) php stuff for displaying stuff in a certain way.

Read More

Having googled a lot, it seems to me the way to do shortcodes is like:

function caption_shortcode( $atts, $content = null ) {
  return '<span class="caption">' . $content . '</span>';
}

My question is, is it possible to put the html in a separate template-ish file? It seems wrong and verbose to put all this markup here, escape quotes, et.c. Like a template-file for a shortcode, to which the shortcode can pass some Data Transfer Object (or simply just some scoped variables). So: display in template-file, logic for finding data (to pass to said template-file) in shortcode-function (wherever it may be defined, functions.php, separate plugin, or something).

Related posts

Leave a Reply

2 comments

  1. You can set-up views(php files) and then include partial views into those ones. WordPress allows templates to be includes within other templates to ensure code reuse and its easily modifiable by child themes. You can use this function to include those

     get_template_part( $slug );
    

    However, in your case, the short code function needs to return the value to the caller function. So, this setup will not work.

  2. For code that effects FUNCTIONALITY, put your code in a plugin.

    For APPEARANCE, put your code in your theme’s template files or funtions.php file.
    Many beggining WP developers lump all their code into the theme’s functions.php file, this is often the wrong place for it (if that code might ever get exported to another theme, for instance). Only put code specific to a specific theme in a theme’s functions.php .
    To get WordPress to recognize your plugin, create a php file and start the file like this:

    <?php
    /*
    Plugin Name: My Caption Shortcode Plugin
    Description: A really cool plugin
    */
    
        function caption_shortcode( $atts, $content = null ) {
            return '<span class="caption">' . $content . '</span>';
        }
    ?>
    

    Put this file in your plugins directory (usually, you should create a sub directory for each plugin). Plugins are usually held in /wp-content/plugins/ . Then you can activate or deactive the code as a plugin, when you go to the plugins tab in the admin menu.

    Of course, this plugin won’t do anything as is. Remember that plugin functionality should be hooked into WordPress via action hooks, filters, and shortcodes. For a shortcode for instance, you’d use the function add_shortcode somewhere to let WordPress know your function is a shortcode.