0

I am Writing a plugin, with many shortcodes. Now I do not want to include all shortcodes source files to every page. So my questions are:

  1. Where should I include the source? Is it back-end or front-end
  2. How to add it on that specific page?

thanks HoGo

1
  • 1
    what do you mean by shortcode source files? js and css? see this question. if it's php, include it in the shortcode handler.
    – Milo
    Jan 6, 2013 at 19:12

3 Answers 3

1

The pattern I use is:

  • break code into modules using classes
  • use spl_autoload_register() to load classes (thereby only included when used)
  • have a class that is the plugin controller, with a method for each shortcode
  • those methods generally do nothing but create instance of shortcode class and pass params

Works for me, simplifies things greatly, especially for large sites where I have dozens of classes. No need to carefully manage what gets included where because the class autoloader handles that.

0

You cannot predict where shortcodes are rendered. Usually in front-end, but there is also AJAX or custom views in back-end.
Include the callback declarations everywhere to be sure.

And if the source file is really that huge, there might be room for refactoring.

0

If its acceptable, I could suggest you to organize your shortcodes by renaming your all shortcodes to make them having the same name and putting old names into an attribute.

For example, if you have 2 shortcodes [shortcode1 ...] and [shortcode2 ...], then new shortcodes will be [myplugin_shortcode action="shortcode1" ...] and [myplugin_shortcode action="shortcode2" ...].

Your plugin index file:

<?php
/*
Plugin Name: bla bla bla
...
*/

add_shortcode('myplugin_shortcode', 'wpse8170_shortcode_handler');
function wpse8170_shortcode_handler($atts, $content = '') {
    $atts = shortcode_atts(array('action' => false), $atts);
    if (empty($atts['action'])) {
        return '';
    }
    require_once 'shortcodes.php';
    return call_user_func_array("wpse8170_shortcode_{$atts['action']}", array($atts, $content));
}

shortcodes.php:

function wpse8170_shortcode_shortcode1($atts, $content = '') {
    return '...';
}

function wpse8170_shortcode_shortcode2($atts, $content = '') {
    return '...';
}

By organizing your shortcodes like this, you will include php file with shortcode functions only when its really required and it doesn't matter if it is admin or frontend page.

2
  • Wrote from phone, sorry for missprints and mistakes Jan 6, 2013 at 20:43
  • Thanks, but i do not want to rename my shortcodes in this way.
    – HoGo
    Jan 7, 2013 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.