Professional WordPress: Design and Development, 3rd Edition (2015)

Chapter 4. Tour of the Core

WHAT’S IN THIS CHAPTER?            

·     Exploring the WordPress core files

·     Searching through core files as reference

·     Working with the WordPress Codex

·     Navigating the WordPress Code Reference

·     Understanding inline documentation

To understand how to extend WordPress properly, you must first learn how the core of WordPress functions. This will help you learn what tools are available in the WordPress core to make your life easier. WordPress handles most of the tedious coding and logic problems for you.

The WordPress core is the best resource for learning how WordPress works. The beauty of open source software is you have all of the code at your disposal. If you are ever unsure how a certain aspect of WordPress functions, just start digging into the code! The answers are all there; it’s just a matter of finding and understanding them.

WHAT’S IN THE CORE?

The WordPress core is powered by a set of files that are part of the original WordPress software download. These are required “core” files that WordPress needs to function properly. The core files are expected to change only when you upgrade WordPress to a newer version.

The core does not include your custom files for plugins, themes, database settings, the .htaccess file, and so on. The core also does not include any media you have uploaded to WordPress. Basically, any files added to WordPress after installation are considered outside of the core.

The WordPress core files are primarily PHP files, but also contain CSS, JavaScript, HTML, and image files. These files control everything about WordPress including how content pages are generated to display, loading the configured theme and plugins, loading all options and settings, and much more. In short, the core contains several major function types:

·     Posts, pages, and custom content—Creating, storing, retrieving, and interacting with the majority of your content in WordPress. The discussion of the loop that controls content display and ordering in Chapter 5 relies heavily on these functions.

·     Post types, taxonomies, and metadata—Everything from custom post types, tags, and categories to user-created taxonomies. The data models used are explored in Chapter 7.

·     Themes—Supporting functions for WordPress themes. Theme development and its relationship to these functions are discussed in Chapter 9.

·     Actions, filters, and plugins—Framework for extending WordPress through plugins, covered in more detail in Chapter 8.

·     Users and authors—Creating and managing access control to your site, and key to the security and enterprise use topics in Chapters 12 and 15.

·     Feeds, formatting, and comments—These are discussed as needed throughout the book.

This chapter digs into these files as you explore the WordPress core files. Think of this chapter as your guidebook to the “how” of exploring the WordPress core; it is a field guide companion to the WordPress Codex documentation for user-contributed discussion and explanation. It’s also imperative to be comfortable browsing and searching the core to complement the functional introduction provided here. An exhaustive list of every WordPress function is not included here, both because the list changes and evolves as the WordPress core undergoes continuous development, and because the goal here is to convey developer and deployer expertise and not to summarize the Codex.

WordPress comes packaged with two plugins: Akismet and Hello Dolly. These two plugins exist in your plugins directory inside wp-content. Even though these two plugins are a part of the WordPress core file package download, they are not considered core functionality because they must be activated to function and can easily be removed.

WordPress also comes packaged with three core themes: Twenty Twelve, Twenty Thirteen, and Twenty Fourteen. Twenty Fourteen is the default theme on a fresh installation of WordPress. As with the included plugins, these theme files are not considered core functionality because they can easily be replaced with any theme that you want to use on your website.

USING THE CORE AS A REFERENCE

Using the WordPress core as a reference is a quick and easy way to learn about various functionality in WordPress. Understanding how to navigate through the WordPress core files can help you find answers to your questions when developing for WordPress.

To use the WordPress core as a reference, you need to understand what to expect in the core files. Most WordPress core files contain documentation in the form of code comments. Typically, a code comment is displayed in the header of the file and gives an overall summary of the core file you are viewing.

To see this first-hand, open the wp-login.php file located in the root directory of WordPress. You’ll notice the top of the file has a header comment describing the file’s function:

/**

 * WordPress User Page

 *

 * Handles authentication, registering, resetting passwords, forgot password,

 * and other user handling.

 *

 * @package WordPress

 */

All core files, other than images, can be viewed using a text editor program. Depending on your default program settings, you may need to open up your text editor first and then open the file rather than just opening up the file directly. It’s also helpful to use a text editor that has syntax highlighting, meaning PHP syntax would be highlighted to help you read the code easier.

There is a full list of compatible text editors on the WordPress.org Codex at http://codex.wordpress.org/Glossary#Text_editor.

Inline Documentation

Nearly all WordPress core files contain inline documentation in PHPDoc form. PHPDoc is a standardized method of describing a function’s usage in PHP comment form. This means each function is explained in detail directly before the function in a comment block. The following is the defined template for documenting a WordPress function:

/**

 * Short Description

 *

 * Long Description

 *

 * @package WordPress

 * @since version

 *

 * @param    type    $varname    Description

 * @return   type                Description

 */

This is amazingly helpful in understanding how functions work. The comment includes a short and long description. It also includes the version of WordPress it was added in. This helps distinguish new functions added to WordPress when a new version is released.

Available parameters are also listed along with the parameter data type. A data type is the type of data that is required for the parameter. For example, an ID parameter would likely use the int (integer) data type. The final piece of information is the return value. The return value data type is also listed.

All new functions added to WordPress are documented using the preceding template. For more information on inline documentation in WordPress, see this Core Contributors Handbook article: http://make.wordpress.org/core/handbook/inline-documentation-standards/php-documentation-standards/.

Finding Functions

Looking up a function in the core is the quickest way to learn how a specific WordPress function works. You can see exactly what parameters are allowed to be sent to the function, as well as what the function actually does and what the return values are.

To start, make sure you have downloaded the latest version of WordPress locally to your computer. You will search these files as a reference for WordPress. Open up any text editor you have that can search files (TextPad for Windows and Sublime Text for Mac are recommended). When searching for a function, you want to eliminate calls to that function from your search. Do this by including the word “function” at the start of your search, as in function wp_head. Not everything in WordPress is a function, but this is a good place to start. If you don’t find any matches, remove “function” from the beginning of your search. Also remember to set your text editor to search all files (*.*), not just .txt files.

Let’s look at the is_super_admin() function. This function is used to check if a user is a super admin in WordPress Multisite. You need to know exactly what values the function expects before you can use it. Open your text editor and search all files in WordPress forfunction is_super_admin. The search should produce one result in wp-includes/capabilities.php:

function is_super_admin( $user_id = false ) {

Right away, you notice one parameter that can be sent to this function: $user_id. Notice the inline documentation listed directly above the function. In this case, the is_super_admin() documentation looks like this:

/**

 * Determine if user is a site admin.

 *

 * @since 3.0.0

 *

 * @param int $user_id (Optional) The ID of a user. Defaults to the current user.

 * @return bool True if the user is a site admin.

 */

This is an extremely valuable block of content. The comment has a short description about what the function does, in this case, “Determine if user is a site admin.” The comment also notes when the function was added (since version 3.0.0). There is also information about the single parameter, including the parameter type, what the parameter is responsible for, and the fact that the parameter is optional in this case. The comment also details what the expected return values will be. In this case, the function will return True if the user is a site admin and False if not.

This alone is enough information to understand how this function works, but let’s dig into the code for a better understanding. The first few lines look like this:

if ( ! $user_id || $user_id == get_current_user_id() )

$user = wp_get_current_user();

else

$user = get_userdata( $user_id );

Based on the PHPDoc comment above the function, you know the $user_id parameter is optional, so this code shows what happens if a $user_id parameter is not passed to the function. The preceding if statement checks if the $user_id variable contains a value. If it does not, or if the current user logged in matches the $user_id, the wp_get_current_user() function is called to get the user data for the currently logged in user. If the $user_id variable contains a value, the get_userdata() function is called to retrieve the user data based on the ID passed to the function.

Next, the function checks that the $user data actually exists before proceeding and, if not, will return false.

if ( ! $user || ! $user->exists() )

    return false;

Now that you know the $user data exists, you need to check if that user is actually a super admin:

if ( is_multisite() ) {

    $super_admins = get_super_admins();

    if ( is_array( $super_admins ) && in_array( $user->user_login,

$super_admins ) )

        return true;

} else {

    if ( $user->has_cap('delete_users') )

        return true;

}

Let’s break down this if statement a bit:

if ( is_multisite() ) {

This if statement checks that Multisite is actually enabled in WordPress by calling the is_multisite() function. Super admins will exist only if the Multisite feature of WordPress has been enabled.

Now that WordPress has determined Multisite is running, the function calls get_super_admins() to retrieve an array of all super admins in WordPress using the following code:

$super_admins = get_super_admins();

The $super_admins variable is now an array of all super admin login usernames. The next line is the most important line in this function. This is the code that actually checks that a user is a super admin in WordPress:

$super_admins = get_super_admins();

if ( is_array( $super_admins ) && in_array( $user->user_login, $super_admins ) )

    return true;

Before working with an array, you always want to verify the variable is an actual array using the is_array() PHP function. The second part of this line of code uses the in_array() PHP function to check if the user’s login exists in the super admin array. If it exists, the user is a super admin and the function returns true.

If the is_multisite() check covered earlier returns false, the function will execute the following else code:

} else {

    if ( $user->has_cap('delete_users') )

        return true;

}

The preceding code checks if the user has the delete_users capability. By default, this capability is assigned to regular administrator accounts in WordPress. If Multisite is disabled in WordPress, but you are an administrator, this code will return true when calling theis_super_admin() function.

The final line of code in the function is:

return false;

This code basically says that if any of the checks in the is_super_admin() function fail, return false. This is more of a safety measure to be certain a true or false value is always returned.

After viewing this example, it should be more apparent how useful the WordPress core code can be. You learned exactly how this function works by exploring the source code. All the answers to your questions exist within the core so it’s essential to have a good understanding of how to utilize the core to your advantage.

Exploring the Core

The WordPress core has certain files that contain many of the more popular WordPress functions. These functions are used for all WordPress APIs and can be used in any custom plugin or theme. The following sections detail the WordPress core files that contain key pieces of code for working with WordPress. All of the files listed in the section that follows are located in the /wp-includes directory of WordPress.

Functions.php

The functions.php file contains the main WordPress API functions. These functions are used to easily interact with WordPress using a standardized method. Plugins, themes, and the WordPress core all use these functions:

·     current_time()—Retrieves the current time based on specified type.

·     force_ssl_login()—Requires SSL (https) login to WordPress.

·     wp_nonce_field()—Adds a nonce hidden field for forms. A nonce field is used for verification purposes when submitting and processing data in WordPress. This is a critical step in securing your code.

·     absint()—Converts value to nonnegative integer.

·     wp_die()—Kills the WordPress execution and displays an HTML error message.

Option.php

The option.php file contains the main WordPress Options API functions. These functions are used for the following:

·     add_option(), update_option(), get_option()—Functions to create, update, and display a saved option.

·     set_transient(), get_transient(), delete_transient()—Functions to create, retrieve, and delete transients in WordPress. A transient is an option with an expiration time. When the expiration time is hit, the transient is automatically deleted in WordPress.

·     add_site_option(), update_site_option(), get_site_option()—Functions to create, update, and display site options. If Multisite is enabled, function returns the network option; if not, the standard site option is returned.

Formatting.php

The formatting.php file contains the WordPress API formatting functions. These functions format the output in many different ways:

·     esc_attr()—Used to escape a string for HTML attributes

·     esc_html()—Used to escape a string for HTML

·     esc_url()—Used to check and clean a URL

·     sanitize_text_field()—Sanitizes a string from user input or from the database

·     is_email()—Verifies that an e-mail is valid

·     capital_P_dangit()—Famous filter that forces the P in WordPress to be capitalized when displaying in content

Pluggable.php

The pluggable functions file lets you override certain core functions of WordPress. WordPress loads these functions if they are still undefined after all plugins have been loaded. Some of the more commonly used functions include:

·     wp_mail()—Sends e-mail from WordPress

·     get_userdata()—Returns all user data from the specified user ID

·     wp_get_current_user()—Returns user data for the currently logged-in user

·     wp_set_password()—Updates a user’s password with a new encrypted one

·     wp_rand()—Generates a random number

·     wp_logout()—Logs out a user, destroying the user session

·     wp_redirect()—Redirects to another page

·     get_avatar()—Returns the user’s avatar

Plugin.php

The plugin.php file contains the WordPress Plugin API functions, including:

·     add_filter()—Hooks that the WordPress core launches to filter content before displaying on the screen or saving in the database

·     add_action()—Hooks that the WordPress core launches at specific points of execution

·     register_activation_hook()—Hook called when a plugin is activated

·     register_deactivation_hook()—Hook called when a plugin is deactivated

·     plugin_dir_url()—Returns the filesystem directory path for the plugin

·     plugin_dir_path()—Returns the URL for the plugin

·     doing_filter() and doing_action()—Returns the name of the current filter or action being processed

User.php

The user.php file contains the WordPress User API functions, including:

·     get_users()—Returns a list of users matching criteria provided

·     add_user_meta(), get_user_meta(), delete_user_meta()—Used to create, retrieve, and delete user metadata

·     username_exists()—Checks if a username exists

·     email_exists()—Checks if an e-mail address exists

·     wp_insert_user() and wp_update_user()—Create and update a user account

Post.php

The post.php file contains the functions used in the post process of WordPress, including:

·     wp_insert_post()—Creates a new post

·     get_post()—Retrieves a single post with all post data

·     get_posts()—Retrieves a list of the latest posts’ matching criteria

·     add_post_meta()—Creates metadata (custom field data) on a post

·     get_post_meta()—Retrieves metadata (custom field data) on a post

·     get_post_custom()—Returns a multidimensional array with all metadata (custom field) entries for a post

·     set_post_thumbnail()—Sets a featured image on a post

·     register_post_type()—Registers a custom post type in WordPress

Taxonomy.php

The taxonomy.php file contains the functions used by the WordPress Taxonomy API. Taxonomies are used to manage the hierarchical relationships of metadata such as categories and tags (described in Chapter 6) and can also be extended, as you’ll explore in Chapter 7. Functions in this file include:

·     register_taxonomy()—Register a custom taxonomy in WordPress

·     get_taxonomies()—Return a list of registered taxonomies

·     wp_insert_term(),wp_update_term()—Insert or update a taxonomy term based on arguments provided

There are many more core functions that can be used when developing custom themes and plugins for WordPress. Take a few minutes and explore the core files inside /wp-includes. This directory contains most of the WordPress API core function files.

To learn more about any function listed here, open up the corresponding file and view the source code. Remember that each function will have inline documentation explaining how to utilize the function correctly. We cover the Plugin API functions in more detail in Chapter 8. The core functions used by themes are covered in Chapter 9.

Deprecated Functions

When a new version of WordPress is being developed, certain functions may become deprecated. A deprecated function means the function is not removed from WordPress, but it should not be used in your plugins and themes going forward. Typically in such a case, a new function has been created to replace the deprecated function. A function may be deprecated in WordPress for many different reasons, but the most common is that the function needs a complete rewrite to better handle the feature it adds to WordPress.

WordPress contains a file to store all functions that have been deprecated over the years. WordPress is known for having superior backwards compatibility. This means that when a new version of WordPress is released, a strong focus it put on backwards compatibility to verify new features and functions will not break existing sites running WordPress, even if the features in use are considered deprecated.

Let’s look at the inline documentation for the get_current_theme() deprecated function:

/**

 * Retrieve current theme name.

 *

 * @since 1.5.0

 * @deprecated 3.4.0

 * @deprecated Use (string) wp_get_theme()

 * @see wp_get_theme()

 *

 * @return string

 */

You’ll notice a few additional comment lines for deprecated functions. The first is the @deprecated line stating in what version of WordPress the function was deprecated, in this case v3.4. The second is @see which tells you what function should be used instead, in this case wp_get_theme().

The deprecated.php file is a very important file to check when a new version of WordPress is released. If a common function is deprecated, you should immediately stop using it and even consider updating your old code to use the replacement.

Generally speaking deprecated functions are usually not removed from the WordPress core, but there is no guarantee a deprecated function won’t be removed in a future release.

WORDPRESS CODEX AND CODE REFERENCE

WordPress has many different online resources that are extremely useful when learning and working with WordPress. These resources should be bookmarked for quick reference and are used by beginners and experts alike.

In this section, we cover the two most popular online WordPress resources: WordPress Codex and the Code Reference.

What Is the Codex?

The WordPress Codex is an online wiki for WordPress documentation located on WordPress.org. WordPress.org describes the Codex as an “encyclopedia of WordPress knowledge.” You can visit the WordPress Codex by going to http://codex.wordpress.org or by clicking the Support ➢ Documentation link in the header of WordPress.org.

The Codex is a wiki-based website, which means anyone can create, edit, and contribute to the articles within the Codex. The Codex is jam-packed with useful knowledge covering all aspects of WordPress. From “Getting Started with WordPress” to more advanced developer topics, the Codex is an essential resource for anyone looking to learn more about WordPress.

The Codex is available in many different languages. To find a Codex version translated into your language, visit the Multilingual Codex page at http://codex.wordpress.org/Multilingual_Codex. You can also contribute to the Codex and help expand on any language or create your own version of the Codex in any language if it is not listed.

Using the Codex

The Codex can be used in many different ways. The most common method is to search the Codex using the search box in the header, or you can visit http://wordpress.org/search/ to easily search through the Codex for appropriate articles matching your search criteria.

The WordPress.org search is powered by Google Custom Search, as shown in Figure 4.1. The search results returned are from all of WordPress.org, not just the Codex, so it’s important to keep that in mind. There is a lesser known Codex-only search located athttp://codex.wordpress.org/Special:Search.

images

Figure 4.1 WordPress.org search

You can also navigate through the index of articles on the Codex homepage. These articles are organized by topic and generally ordered by level of difficulty. There is also a topic toward the top for the latest version of WordPress. The articles here cover new features, compatibility tests for plugins and themes, installing, upgrading, and support for the new version.

An extensive glossary of terms is available for the Codex. This can help familiarize you with common words used throughout the Codex. You can view the official Codex Glossary at http://codex.wordpress.org/Glossary.

Another search method is to use the quick index. This index allows you to look up an article by the first letter of the article’s title. You can find the quick index at http://codex.wordpress.org/Codex:Quick_index.

A WordPress Lessons page is also featured in the Codex at http://codex.wordpress.org/WordPress_Lessons. This page provides lessons on how to learn specific elements of WordPress. The lessons are organized by topic and are a great place to start if you are unsure what to read first.

Function Reference

WordPress functions are described in the Codex with an individual Function Reference page for each WordPress API function available. These pages explain in detail exactly how a WordPress function works, as shown in Figure 4.2. Bookmark this page for a quick reference on WordPress functions and their capabilities. The official Function Reference is located at http://codex.wordpress.org/Function_Reference.

images

Figure 4.2 Function reference for get_userdata()

Think of the Function Reference as an online and expanded version of a function’s inline documentation. The reference has a description explaining how the function works and how it is used. The individual parameters are listed along with data types and a description of each.

The most useful section of the Function Reference is the Examples section of the page. The examples make it very easy to see exactly how to use the function. The get_userdata() example is shown here:

<?php $user_info = get_userdata(1);

      echo 'Username: ' . $user_info->user_login . "\n";

      echo 'User roles: ' . implode(', ', $user_info->roles) . "\n";

      echo 'User ID: ' . $user_info->ID . "\n";

?>

This example shows how to load specific user data for user ID 1. The example output is as follows:

Username: michael_myers

User Level: administrator

User ID: 1

This is a simple example, but this, along with the additional reference information, can help you easily learn a new function and how to use it properly in your code.

The Source File section of the Function Reference details where the function is located in the WordPress core. In our example, the get_userdata() function is located in wp-includes/pluggable.php. The location file is a link that points to the WordPress core file in Trac. This is a quick and handy way to view where the function is declared via your browser. We cover the Trac software in Chapter 16.

The final Function Reference topic lists Related functions. This can help you identify a similar function that may accomplish that task you are working on. For example, the wp_insert_post() function lists wp_update_post() and wp_delete_post() as related functions.

The majority of the WordPress API functions are well documented, but not all functions have a Function Reference page in the Codex. Any function displayed in red on the Function Reference homepage currently has no documentation. This is an ongoing community project so expect all functions to be fully documented in the Codex eventually.

NOTE  Contributing to the Codex is a great way to get involved in WordPress. You don’t need to be an advanced developer to contribute code examples, descriptions, and additional information about various features and functions in WordPress.

WordPress APIs

WordPress features many different APIs that help interact with WordPress. Think of the APIs as gateways that let you add functionality or retrieve external content within WordPress without violating the “don’t hack the core” maxim: Most APIs insert references to non-core code that will be added to the wp-content directory by registering its entry points with WordPress. Each API is documented in the Codex along with functions used in the API. An API is a set of predefined functions available for use in themes and plugins. The following is a list of the most common WordPress APIs:

·     Plugin API—Used for custom plugin development. The Codex features an extensive Plugin API documentation page. There is an introduction to hooks, actions, and filters, the primary ways to interact with WordPress from a custom-built plugin. The Plugin API page links to the Function Reference pages for available API functions are located in /wp-includes/plugins.php at http://codex.wordpress.org/Plugin_API.

·     Widgets API—Used to create and maintain widgets in your plugin. The widget will automatically appear under the Appearance ➢ Widgets screen and can be used on any defined sidebar on your theme. The widgets API is located athttp://codex.wordpress.org/Widgets_API.

·              Shortcode API—Used for adding shortcodes in your plugin. A shortcode is a macro code added to a post. This allows a plugin to grab that shortcode and execute specific commands and display elements in place of it in your post. Shortcodes can also accept parameters to alter the output.

An example core WordPress shortcode is [gallery]. Adding [gallery] to your post automatically displays all images uploaded to that post in a gallery style. When editing a post, you will see the [gallery] shortcode, but viewing it on the public side of your website displays the actual gallery of images. The shortcode API is found at http://codex.wordpress.org/Shortcode_API.

·              HTTP API—Used for sending an HTTP request from WordPress. This API is a standardized method to grab the content of an external URL. Basically, it takes the provided URL and tests a series of PHP methods for sending the request. Depending on the hosting environment, WordPress uses the first method it deems to be configured correctly to make the HTTP request.

The current HTTP API PHP methods tested are cURL, Streams, and FSockopen. The methods are also checked exactly in that order. You can use the Core Control plugin (http://wordpress.org/extend/plugins/Core-control/) to specifically choose which method is used for all HTTP requests.

Using the HTTP API, you could easily interact with the Google Maps API to dynamically generate maps and plots. The HTTP API can also easily interact with the Twitter API, allowing you to post/read tweets directly from WordPress. The HTTP API is found athttp://codex.wordpress.org/HTTP_API.

·     Settings API—Used for creating a settings page. This API is used for creating and managing custom options for your plugins and themes. The main advantage of using the Settings API is security. The API sanitizes all of the setting data saved by the user. This means no more worrying about nonces, data validation, and cross-site scripting (XSS) attacks when saving setting data. This is much easier than the old method of data validation, which you had to use each time you needed to save settings in a plugin. The settings API is found at http://codex.wordpress.org/Settings_API.

·     Options API—Used for storing option data in the WordPress database. The Options API provides an easy way to create, update, retrieve, and delete option values. The options API is found at the following URL: http://codex.wordpress.org/Options_API

·     Dashboard Widgets API—Used for creating admin dashboard widgets. Widgets added from the API automatically contain all jQuery features that the core admin dashboard widgets have, including drag/drop, minimize, and hiding via screen options. The dashboard widgets API is found at http://codex.wordpress.org/Dashboard_Widgets_API.

·     Rewrite API—Used for creating custom rewrite rules. This API allows you to create custom rewrite rules just as you would in your .htaccess file. You can also create custom permalink structure tags (that is, %postname%), add static endpoints (that is, /my-page/), and even add additional feed links. The Rewrite API functions are located in /wp-includes/rewrite.php at http://codex.wordpress.org/Rewrite_API.

Remember that all WordPress APIs can be used in custom plugin and theme development. This is the primary method of extending WordPress with additional features and functionality. Utilizing the preceding APIs creates an easy and standardized way of interacting with WordPress.

For more information on all WordPress APIs visit the Codex page at http://codex.wordpress.org/WordPress_API's.

Codex Controversy

As with any wiki, there will always be controversy over the accuracy of the articles in the Codex. One problem that has plagued the Codex is the freshness of the articles. WordPress is being developed at a decent pace and thus the Codex needs to keep up that pace in order to be accurate. Unfortunately, that doesn’t always happen, and some material is outdated. The WordPress Codex is a community project, so you can easily create an account and start helping out! Contributing to WordPress is covered in Chapter 16.

Another problem that exists within the Codex is the organization of the content. Currently, there is so much information in the Codex that it can be hard and confusing to find the answers you are looking for. Again, one of the motivations for this introduction to the WordPress core is to provide you with a map to help narrow the scope of your searches and to introduce related functional topics.

Code Reference

The WordPress Code Reference is a newer online resource for WordPress. Launched in the spring of 2014, the Code Reference is an auto-generated online resource to help developers find more information on WordPress functions, classes, hooks, and more. You can visit the Code Reference by going to http://developer.wordpress.org/reference/.

The Code Reference content is generated using an open source project called WP Parser. This program parses through all WordPress core files and generates the reference entries from the WordPress core inline documentation. For more information on the WP Parser project, and to get involved, visit https://github.com/rmccue/WP-Parser.

Using the Code Reference

There are a few different ways you can use the Code Reference. As with all WordPress online documentation, a powerful search option is available. Searching the Code Reference can help you find a particular function you may be looking for if you don’t know the name.

Alternately, you can browse various topics, including functions, hooks, classes, and methods. Filtering by topic will list all topics in alphabetical order and is a great way to learn about topics you may be less familiar with.

Another very valuable feature of the Code Reference is the ability to see all functions by WordPress version. For example, you can see all functions that were introduced in WordPress 4.0.0 by visiting http://developer.wordpress.org/reference/since/4.0.0/. To view older versions of WordPress, simply change the version in the URL to the version you’d like to see. If you need to see what functions were introduced in WordPress 2.5, visit http://developer.wordpress.org/reference/since/2.5.0/.

Code Reference Details

Every entry in the Code Reference has a detail page that lists all information about that entry. Let’s look at the absint() WordPress function as an example, as shown in Figure 4.3.

images

Figure 4.3 WordPress Code Reference for absint()

The first section of the Code Reference includes the function with available parameters, a description about the function, the return value to expect, what version of WordPress the function was added to, and the source file where the function is declared. If you think this information looks familiar, you are absolutely right. The function details shown on the Code Reference page are pulled directly from the inline documentation for the absint() function in WordPress core.

The function parameters are detailed next. This section will list any and all parameters the function will accept. Each parameter is detailed along with the data type the function is expecting.

The final section is the actual source for the function declaration. This code is exactly what exists in the WordPress core for the function we are viewing. As you can see, the WordPress Code Reference is an online, prettier version of the actual WordPress core code.

Codex Versus Code Reference

The biggest benefit to the Code Reference over the Codex is accuracy. The Code Reference is automatically generated from the WordPress core files. This ensures all content in the Code Reference is completely accurate and always up to date with the latest version of WordPress. The WordPress Codex, on the other hand, is a wiki that is manually updated by contributors from all over the world.

The biggest benefit to the Codex over the Code Reference is the additional amount of content and examples provided. Because the Codex is a wiki, an unlimited amount of information, examples, and tutorials can exist for any given feature and function in WordPress. This can make understanding how to work with a specific function in WordPress much easier to grasp initially.

The Codex and the Code Reference have pros and cons, but ultimately they are two very good resources for learning to develop with WordPress and should be bookmarked for future reference.

DON’T HACK THE CORE!

Whereas exploring the WordPress core and using it as a reference is highly encouraged, hacking the core is not. Hacking the core means making any changes to the core files of WordPress. A change could be as simple as one line of code, but a hack is a hack and doing so could cause major problems down the road.

Why Not?

Hacking the WordPress core can make it very difficult to update to the latest version of WordPress. Keeping WordPress current is an important step in overall website security. If any security vulnerability is discovered, a patch is typically released very quickly. If you can’t update because you have modified core files, you are opening up your website to these security vulnerabilities, and you increase the likelihood that your website will be hacked.

Hacking the core can also lead to an unstable website because many parts of WordPress rely on other parts to function as expected. If you make changes to those parts, it could break something completely unrelated to what you have changed.

Security is another reason why you shouldn’t hack the core. WordPress core is viewed and scrutinized by security experts all over the world. By hacking the core, you are relying on your own expertise to make your hacks secure. If you don’t understand the many different ways a hacker can exploit your code, you might end up creating a security vulnerability within the core of WordPress.

The final reason why you should never hack the core is compassion: that is, compassion toward the developer who comes after you to maintain the website. Most websites will change developers over the years so there is no guarantee you will be working on a particular website five years from now. Imagine the developer that follows you trying to determine what core files were hacked to make the website function. This can be a nightmare for any developer and it puts the website owner in a bad position because most developers will refuse to work on a hacked version of WordPress. If you hack the core, you are building dependencies that will either be misunderstood or hidden, and when the WordPress core is upgraded for this site, the hacked core will break in silent, evil, or loud ways.

Alternatives to Hacking the Core

Any feature or functionality that does not exist in WordPress can be added with a plugin. Sometimes a core hack may be the easy answer, but in the long run, it will make your life harder. (We have yet to come across a feature we needed that we couldn’t incorporate with a plugin.) WordPress is extremely flexible, which is one of its major strengths, and therefore the core should never be hacked. Don’t hack the core!

If you are fascinated by the WordPress core and its intricacies, you should join the WordPress Developer Community and get involved fixing bugs and contributing to the core build of WordPress. This is covered in detail in Chapter 16.

SUMMARY

In this chapter, you covered a tour of the WordPress core software. You explored what’s in the core, how to use the core as a reference when developing for WordPress, and how to determine what functions are deprecated each release. You also learned about the WordPress Codex, the Code Reference, and the most commonly used APIs in WordPress.

Now that you understand the core of WordPress, it’s time to learn how to utilize the WordPress Loop to customize the display of content.