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

Using WordPress path utility functions to load external files and images

On occasion, plugins need to refer to external files (for example, images, JavaScript, or jQuery script files) that are stored in the plugin directory. Since users are free to rename a plugin's folder or even install plugin files straight into the WordPress plugins directory, paths to any external files must be built dynamically based on the actual plugin location. Thankfully, a number of utility functions are present to simplify this task.

How to do it...

Follow these steps to create a simple plugin that will add a favicon meta tag to a website's header, pointing to an image file located in the plugin's directory:

  1. Navigate to the WordPress plugins directory of your development installation.
  2. Create a new directory called ch2-favicon.
  3. Use a web service, such as https://favicongrabber.com/, to retrieve a website's favicon (for example, https://www.packtpub.com) and store it in the ch2-favicon directory with its default name (favicon.ico).
  4. Navigate to the ch2-favicon directory and create a new text file called ch2-favicon.php.
  5. 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 - Favicon.
  6. Add the following line of code to register a function that will be called when WordPress renders the page header:
    add_action( 'wp_head', 'ch2fi_page_header_output' );
  7. Add the following code section to provide an implementation for the ch2fi_page_header_output function:
    function ch2fi_page_header_output() {
        $site_icon_url = get_site_icon_url();
        if ( !empty( $site_icon_url ) ) {
            wp_site_icon();
        } else {
            $icon = plugins_url( 'favicon.ico', 
                                 __FILE__ );
        ?>
        <link rel="shortcut icon"
              href="<?php echo esc_url( $icon ); ?>" />
        <?php }
    }
  8. Save and close the plugin file.
  9. Log in to the administration page of your development WordPress installation.
  10. Click on Plugins in the left-hand navigation menu.
  11. Activate your new plugin.
  12. Navigate to your website's front page and refresh it to see that the icon file that you assigned through your plugin code now appears in your browser's address bar, title bar, or navigation tab, depending on your preferred browser. The following screenshot shows how the favicon file is rendered in Microsoft Edge, Google Chrome, and Mozilla Firefox, from top to bottom:
Figure 2.3 – The website favicon appearing in Microsoft Edge, Google Chrome, and Mozilla Firefox

Figure 2.3 – The website favicon appearing in Microsoft Edge, Google Chrome, and Mozilla Firefox

  1. Go to the Appearance section of your development site's Dashboard and Activate a theme other than Twenty Twenty-Two (for example, Twenty Twenty-One or Twenty Twenty). You may need to install one of these themes if they are not present in your development environment.
  2. Select the Customize submenu under the Appearance menu.
  3. Under Site Identity, assign a square image that is at least 512 x 512 pixels in dimension as the Site Icon; then, click the Publish button at the top of the customizer.
  4. Refresh your website to see that the newly assigned site icon image is now displayed instead of the favicon.ico file.
  5. Go back to the Appearance section and Activate the Twenty Twenty-Two theme.

How it works...

The plugins_url utility function, used in conjunction with the __FILE__ PHP constant and the name of our favicon file, allows us to quickly get the URL of this file located in our plugin directory. Once we have it, we can print out the appropriate HTML command to notify browsers of the location of this file.

The plugins_url function can be called with or without parameters. In the first case, it builds a URL by appending the path or filename found in the first parameter to the location of the file specified in the second argument. In the second situation, it simply returns the location of the plugin directory:

plugins_url( $path, $plugin );

Before we display our plugin's favicon file, we also call the get_site_icon_url function to see whether the user has already assigned a site icon using the WordPress customizer. If that is the case, we give priority to that icon and display it using the wp_site_icon() function.

Note

The Twenty Twenty-Two theme found in WordPress 5.9 is built using a new theme creation technique and does not have a customizer section. This is why we change our site theme to demonstrate how our code takes into consideration site icons assigned in the customizer. The majority of themes available today have customizer sections, but this may change as WordPress evolves. The Twenty Twenty-Two theme may also add a customizer section in future releases.

There's more...

The plugins_url function is one of the many functions that can be used in plugins to help find the location of files in a WordPress installation. Other useful functions include the following:

  • get_theme_root(): Returns the address of the theme installation directory
  • get_template_directory_uri(): Retrieves the URL to the current theme's files
  • admin_url(): Provides the address of the WordPress administrative pages
  • content_url(): Indicates where the wp-content directory can be found
  • site_url() and home_url(): Returns the site address
  • includes_url(): Provides the location of WordPress include files
  • wp_upload_dir(): Indicates the directory where user-uploaded files are stored

See also

  • The Creating a plugin file and header recipe
  • The Adding output content to page headers using plugin actions 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