Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying WordPress Plugin Development Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
WordPress Plugin Development Cookbook

WordPress Plugin Development Cookbook - Second Edition

By : Yannick Lefebvre
4.4 (12)
close
close
WordPress Plugin Development Cookbook

WordPress Plugin Development Cookbook

4.4 (12)
By: Yannick Lefebvre

Overview of this book

WordPress is a popular, powerful, and open Content Management System. Learning how to extend its capabilities allows you to unleash its full potential, whether you're an administrator trying to find the right extension, a developer with a great idea to enhance the platform for the community, or a website developer working to fulfill a client's needs. This book shows readers how to navigate WordPress' vast set of API functions to create high-quality plugins with easy-to-configure administration interfaces. With new recipes and materials updated for the latest versions of WordPress 4.x, this second edition teaches you how to create plugins of varying complexity ranging from a few lines of code to complex extensions that provide intricate new capabilities. You'll start by using the basic mechanisms provided in WordPress to create plugins and execute custom user code. You will then see how to design administration panels, enhance the post editor with custom fields, store custom data, and modify site behavior based on the value of custom fields. You'll safely incorporate dynamic elements on web pages using scripting languages, and build new widgets that users will be able to add to WordPress sidebars and widget areas. By the end of this book, you will be able to create WordPress plugins to perform any task you can imagine.
Table of Contents (13 chapters)
close
close

Creating a new shortcode with parameters

Simple shortcodes already provide a lot of potential to output complex content to a page by entering a few characters in the post or page editors. That being said, they become even more useful when they are coupled with parameters that will be passed to their associated processing function. Using this technique, it becomes very easy to create a shortcode that accelerates the insertion of external content in WordPress posts or pages by only needing to specify the shortcode and the unique identifier of the source element to be displayed.

How to do it...

Follow these steps to create a shortcode that will be used to quickly add Twitter feeds to posts or pages:

  1. Navigate to the WordPress plugins directory of your development installation.
  2. Create a new directory called ch2-twitter-embed.
  3. Navigate to this directory and create a new text file called ch2-twitter-embed.php.
  4. Open the new file in a code editor and add an appropriate header at the top of the plugin file, naming the plugin Chapter 2 - Twitter Embed.
  5. Add the following line of code to declare a new shortcode and specify the name of the function that should be called when the shortcode is found in posts or pages:
    add_shortcode( 'twitterfeed', 
                   'ch2te_twitter_embed_shortcode' );
  6. Add the following code section to provide an implementation for the ch2te_twitter_embed_shortcode function:
    function ch2te_twitter_embed_shortcode( $atts ) {
        extract( shortcode_atts( array(
            'user_name' => 'ylefebvre'
        ), $atts ) );
        if ( empty( $user_name ) ) {
            $user_name = 'ylefebvre';
        } else {
            $user_name = 
                sanitize_text_field( $user_name );
        }
        $output = '<p><a class="twitter-timeline" href="';
        $output .= 
            esc_url( 'https://twitter.com/'.$user_name );
        $output .=
            '">Tweets by ' . esc_html( $user_name );
        $output .= '</a></p><script async ';
        $output .=
            'src="//platform.twitter.com/widgets.js"';
        $output .= 'charset="utf-8"></script>';
        return $output;
    }
  7. Save and close the plugin file.
  8. Log in to the administration page of your development WordPress installation.
  9. Click on Plugins in the left-hand navigation menu.
  10. Activate your new plugin.
  11. Create a new page and use the [twitterfeed user_name='WordPress'] shortcode in the page editor, where WordPress is the Twitter username of the feed to display:
    Figure 2.11 – Inserting the Twitter feed shortcode with its user_name parameter

Figure 2.11 – Inserting the Twitter feed shortcode with its user_name parameter

  1. Publish and view the page to see that the shortcode has been replaced by an embedded Twitter feed on your site. The Twitter feed may be quite large, based on the theme you are using on your development site.
  2. Edit the page and remove the user_name parameter and its associated value, only leaving the core [twitterfeed] shortcode in the post; then Update to save changes.
  3. Refresh the page to see that the feed is still being displayed but now shows tweets from a default account specified by the code.

How it works...

When shortcodes are used with parameters, these extra pieces of data are sent to the associated processing function in the $atts parameter variable. By using a combination of the standard PHP extract and WordPress-specific shortcode_atts functions, our plugin is able to parse the data it receives and create an array of identifiers and values that are subsequently transformed into PHP variables. These variables are used in the rest of our shortcode implementation function. In this specific example, we expect a single variable to be used, called user_name, which will be stored in a PHP variable called $user_name. If the user enters the shortcode without any parameter, a default value of ylefebvre will be assigned to the $user_name variable to ensure that the plugin still works. Since we are going to accept user input in this code, we also verify that the user did not provide an empty string. We also use the sanitize_text_field function to make sure that there is no hazardous code in what the user entered, along with the esc_html and esc_url functions to be absolutely sure to remove any potentially harmful HTML characters before we output the destination link and its accompanying text to the browser.

Once we have access to the Twitter username, we can put together the required HTML code that will embed a Twitter feed in our page and display the selected user's tweets.

While this example only has one argument, it is possible to define multiple parameters for a shortcode. In such a situation, parameters can be provided in any order by the user.

See also

  • The Creating a new simple shortcode recipe
Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
WordPress Plugin Development Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon