WordPress: create a plugin to include external content

A WordPress Plugin is a program, or a set of one or more functions, written in the PHP scripting language, that adds a specific set of features or services to the WordPress weblog, which can be seamlessly integrated with the weblog using access points and methods provided by the WordPress Plugin Application Program Interface (API).

The first option is to create a PHP file with a name derived from your chosen Plugin name. For instance, if your Plugin will be called “Demo”, you might call your PHP file demo.php. Try to choose a unique name. People who install your Plugin will be putting this PHP file into the WordPress Plugins directory in their installation (usually wp-content/plugins/), so no two Plugins they are using can have the same PHP file name.

Another option is to split your Plugin into multiple files. Your WordPress Plugin must have at least one PHP file; it could also contain JavaScript files, CSS files, etc. If there are multiple files, pick a unique name for a directory and a name of your choice (usually the same) for the main PHP file of your Plugin, such as demo and demo.php, respectively, put all your Plugin’s files into that directory, and tell your Plugin users to install the whole directory under wp-content/plugins/. Notice that WordPress installation can be configured for wp-content/plugins/ directory to be moved, so you must use plugin_dir_path() and plugins_url() for absolute paths and URLs.

The top of your Plugin’s main PHP file must contain a standard Plugin information header. This header lets WordPress recognize that your Plugin exists, add it to the Plugin management screen so it can be activated, load it, and run its functions; without the header, your Plugin will never be activated and will never run. Important: file must be in UTF-8 encoding. Here is the header format:

/**
 * Plugin Name: Name Of The Plugin
 * Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
 * Description: A brief description of the Plugin.
 * Version: The Plugin's Version Number, e.g.: 1.0
 * Author: Name Of The Plugin Author
 * Author URI: http://URI_Of_The_Plugin_Author
 * License: A "Slug" license name e.g. GPL2
 */

Many WordPress Plugins accomplish their goals by connecting to one or more WordPress Plugin “hooks“. The way Plugin hooks work is that at various times while WordPress is running, WordPress checks to see if any Plugins have registered functions to run at that time, and if so, the functions are run. These functions modify the default behavior of WordPress.

Another way for a WordPress Plugin to add functionality to WordPress is by creating custom Template Tags. Someone who wants to use your Plugin can add these “tags” to their theme, in the sidebar, post content section, or wherever it is appropriate. For instance, a Plugin that adds geographical tags to posts might define a template tag function called geotag_list_states() for the sidebar.

Most WordPress Plugins will need to get some input from the site owner or blog users and save it between sessions, for use in its filter functions, action functions, and template functions. This information has to be saved in the WordPress database, in order to be persistent between sessions. There are 4 methods for saving Plugin data in the database:

  • Use the WordPress “option” mechanism. This method is appropriate for storing relatively small amounts of relatively static, named pieces of data
  • Post Meta (a.k.a. Custom Fields). Appropriate for data associated with individual posts, pages, or attachments
  • Custom Taxonomy. For classifying posts or other objects like users and comments and/or for a user-editable name/value list of data consider using a Custom Taxonomy.
  • Create a new, custom database table. This method is appropriate for data not associated with individual posts, pages, attachments, or comments

Assuming that your Plugin has some options stored in the WordPress database, you will probably want it to have an administration panel that will enable your Plugin users to view and edit option values. To add an administration menu, you must do three things:

  • Create a function that contains the menu-building code
  • Register the above function using the admin_menu action hook (If you are adding an admin menu for the Network, use network_admin_menu instead)
  • Create the HTML output for the page displayed when the menu item is clicked

This plugin will add a sub-level menu item under the Settings top-level menu, and when selected, that menu item will cause a very basic screen to display. Note: this code should be added to a main plugin PHP file or a separate PHP include file.

add_action('admin_menu', 'demo_menu');
add_shortcode('demo', 'render_demo');
 
function demo_menu() {
	add_options_page( 'Demo Options', 'Demo', 'manage_options', 'demo12345', 'demo_options' );
}
 
function demo_options() {
	if (!current_user_can('manage_options'))  {
		wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
	}
 
	// Variables for the field and option names 
    $opt_name = 'demo_name';
    $hidden_field_name = 'demo_submit_hidden';
    $data_field_name = 'demo_name';
 
    // Read in existing option value from database
    $opt_val = get_option($opt_name);
 
	// See if the user has posted us some information
    // If they did, this hidden field will be set to 'Y'
    if (isset($_POST[$hidden_field_name]) && $_POST[$hidden_field_name] == 'Y') {
        // Read their posted value
        $opt_val = $_POST[$data_field_name];
 
        // Save the posted value in the database
        update_option($opt_name, $opt_val);
 
        // Put an settings updated message on the screen
		echo '<div class="updated"><p><strong>' . __('Settings saved.', 'menu-test') . '</strong></p></div>';
	}
?>
	<div class="wrap">
		<h2><?php echo __( 'Demo Plugin Settings', 'menu-test') ?></h2>
		<form name="demo_settings_form" method="post" action="">
			<input type="hidden" name="<?php echo $hidden_field_name; ?>" value="Y">
			<p><?php _e("Naam:", 'menu-test' ); ?> 
				<input type="text" name="<?php echo $data_field_name; ?>" value="<?php echo $opt_val; ?>" size="20">
			</p>
			<hr />
			<p class="submit">
				<input type="submit" name="Submit" class="button-primary" value="<?php esc_attr_e('Opslaan') ?>" />
			</p>
		</form>
	</div>
<?php }
 
function render_demo() {
	$response = wp_remote_get('http://codex.wordpress.org');
	return  $response['body'];
}

The Shortcode API is a simple set of functions for creating macro codes for use in post content. It enables plugin developers to create special kinds of content (e.g. forms, content generators) that users can attach to certain pages by adding the corresponding shortcode into the page text. The API handles all the tricky parsing. Helper functions are included for setting and fetching default attributes. The API supports both self-closing and enclosing shortcodes.

Shortcode names should be all lowercase and use all letters, but numbers and underscores should work fine too. Be wary of using hyphens (dashes), you’ll be better off not using them. Three optional parameters can be passed to the shortcode callback function:

  • $atts – an associative array of attributes, or an empty string if no attributes are given
  • $content – the enclosed content (if the shortcode is used in its enclosing form)
  • $tag – the shortcode tag, useful for shared callback functions

When the content (i.e. post) is displayed, the shortcode API will parse any registered shortcodes such as “[mydemoshortcode]”, separate and parse the attributes and content, if any, and pass them the corresponding shortcode handler function. Any string returned (not echoed) by the shortcode handler will be inserted into the post body in place of the shortcode itself. Don’t use camelCase or UPPER-CASE for your $atts attribute names.

The wp_remote_get function is part of the HTTP API and can be used to retrieve the raw response from the HTTP request using the GET method. Results include HTTP headers and content.


Leave a Reply