Is it possible to have predefined chunks of code that can be inserted into the editor/textarea when making a new page?

On my site i have a listing of local people, and although each page has different content, the way that content is displayed is the same (tables, headings etc). When adding a new person i need to manually type out the markup (or copy and paste from a previous page). I just need a snippet when adding a new page that provides the tabular structure for me to add the new person data to.

Or maybe a custom button that can be added to the toolbar, that inserts the table html?


Use shortcodes with as many attributes as you want.

add_shortcode('custom-display-of-data', 'custom_display_of_data');

function custom_display_of_data($atts) {
    $atts = shortcode_atts(
            'foo' => false, // default foo is false
            'bar' => 'default bar', // default bar is string: default bar
            // define defaults for as many attributes you need
        ), $atts, 'custom-display-of-data' );
    // place your code here to return the content you want 
    // based on values of your attributes
    // and place it in a variable. (i use $output)
    return $output;

Now you can use [custom-display-of-data foo="my foo" bar="my bar"] inside your posts and it will echo the returned result of the function custom_display_of_data() with the attributes you passed. The only limitation is that you need to pass data as strings so, if you want to pass arrays or objects you might want to add them in json format and decode them in your function.

Remember that you need to return the output of the function, not echo it. If it's not obvious, you should change the names of the shortcode, function and attributes to anything you like, but a good practice is to prefix the shortcode and the function name with something that ensures their uniqueness. If any plugin or theme uses the same function or declares the same shortcode as yours you will run into some php warnings.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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