
WordPress Plugin Development Cookbook
By :

When a plugin adds custom content or inserts styling tags to a post or page's existing content, as was done in the previous recipe that showed how to create an enclosing shortcode, it often needs to load a custom style sheet to style these new elements. This recipe shows how to add a style sheet in the WordPress style queue to format the private output created in the previous recipe. This queue is processed when the page header is rendered, listing all the style sheets that need to be loaded to display the site correctly.
You should have already followed the Creating a new enclosing shortcode recipe to have a starting point for this recipe, and the resulting plugin should still be active in your development site. Alternatively, you can download the resulting code (ch2/ch2-private-item-text/ch2-private-item-text.php
) of that recipe from the book's GitHub page.
Follow these steps to add insert custom Cascading Style Sheet (CSS) code in your page output:
ch2-private-item-text
folder of the WordPress plugins
directory of your development installation.ch2-private-item-text.php
file in a code editor.add_action( 'wp_enqueue_scripts', 'ch2pit_queue_stylesheet' );
ch2pit_queue_stylesheet
function:function ch2pit_queue_stylesheet() { wp_enqueue_style( 'privateshortcodestyle', plugins_url( 'stylesheet.css', __FILE__ ) ); }
ch2-private-item-text
directory called stylesheet.css
and open it in a code editor..private { color: #6E6A6B; } .register { background-color: #ff4d4d; color: #fff; padding-left: 10px; }
While it would have been possible to write straight HTML code to load the CSS file by registering a function with the wp_head
action hook, as we have done previously, WordPress has utility functions designed to help avoid loading duplicate style sheets or scripts on a site. In this specific example, wp_enqueue_script
is used to place the plugin's style sheet file in a queue that will be processed when the plugin header is rendered, with the associated name privateshortcodestyle
. Once WordPress has processed all the plugins and boiled down all the style sheet requests to single instances, it will output the necessary HTML code to load all of them.
The content of the stylesheet.css
file is standard CSS code that specifies that any text that is assigned the private
class should be displayed in gray, while the text displayed to non-registered users should be displayed in white on a red background.