Lessons Learned: Outputting Shortcode and Plugin Results

If you look closely at the documentation for WordPress Shortcodes, there is a specific way to output content to the screen. Of course, this is a part of the documentation I skipped while developing my first plugin which lead to some baffling results. To help save you time, I wanted to share one last lesson learned from writing my plugin.

Background

A few weeks back, I posted a version of the code for my first WordPress plugin (My First WordPress Plugin: Generates a Bulleted List of Clickable Blog Post Titles). The plugin allows you to pass any category name through a WordPress Shortcode. The plugin then displays clickable links for the posts under that category as a bullet list.

The plugin was initially set up as follows:

<?php
/*
Plugin Name: Simple Post List
Description: Displays a list of clickable blog post titles based on the specified category. To specify the category, a shortcode like <strong>[postlist cat="FAQ"]</strong> can be added to your page.
Author: Patrick Nichols
*/
function display_post_list($args){
     //...
 
     //DISPLAY RESULT
     print '<ul>' . implode($postLinks) . '</ul>';
}
 
//ACTIVATE THE "postlist" SHORTCODE
add_shortcode('postlist', 'display_post_list');
?>

The bulleted list displayed as expected during the initial development. But that all changed when I got into the final testing phase for the plugin.

The Problem

To speed things up, I wanted to add several shortcodes to a page. Each shortcode was separated with a quick sentence describing the shortcode.

Posts for the "FAQ" category:
[postlist cat="FAQ"]
 
Posts for the "Courses" category:
[postlist cat="Courses"]
 
Posts for the "News" category:
[postlist cat="News"]

Well, the sentences and bulleted lists from the plugin all appeared. But the sentences were pushed to the bottom of the page instead of being sentence, bulleted list, sentence, bulleted list, etc.

The Solution

It turns out that shortcodes are processed before the other page content. To fix the issue, I just needed to return the output instead of printing it.

<?php
/*
Plugin Name: Simple Post List
Description: Displays a list of clickable blog post titles based on the specified category. To specify the category, a shortcode like <strong>[postlist cat="FAQ"]</strong> can be added to your page.
Author: Patrick Nichols
*/
function display_post_list($args){
     //...
 
     //DISPLAY RESULT
     return '<ul>' . implode($postLinks) . '</ul>';
}
 
//ACTIVATE THE "postlist" SHORTCODE
add_shortcode('postlist', 'display_post_list');
?>

Related Posts

0 Comments

There are currently no comments.

Leave a Comment