Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore Professional WordPress Design and Development

Professional WordPress Design and Development

Published by ainmohd, 2016-11-16 15:48:20

Description: Professional WordPress is the only WordPress book targeted to developers, with advanced content that exploits the full functionality of the most popular CMS in the world. Fully updated to align with WordPress 4.1, this edition has updated examples with all new screenshots, and full exploration of additional tasks made possible by the latest tools and features. You will gain insight into real projects that currently use WordPress as an application framework, as well as the basic usage and functionality of the system from a developer's perspective. The book's key features include detailed information and real-world examples that illustrate the concepts and techniques at work, plus code downloads and examples accessible through the companion website. Written by practicing WordPress developers, the content of this edition focuses on real world application of WordPress concepts that extend beyond the current WordPress version.

WordPress started in 2003 with a single bit of code to...

Search

Read the Text Version

WordPress Codex and Resources ❘ 73 latest version of WordPress. The articles here cover new features, compatibility tests for plugins and themes, installing, upgrading, and support for the new version. There is also an extensive glossary of terms 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 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 lists out 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 Word- Press 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. FIGURE 4-2: Function reference for get_userdata Think of the Function Reference as an online and expanded version of a function’s inline documen- tation. 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.

74 ❘ CHAPTER 4 TOUR OF THE CORE The most useful section of the Function Reference is the examples toward the bottom. 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 level: ‘ . $user_info->user_level . \"\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: admin User Level: 10 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 final Function Reference topic lists related functions. This can help 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 Func- tion 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. WordPress APIs WordPress features many different APIs that help interact 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 current 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. These are 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. These functions are located in /wp-includes/plugins.php. http://codex.wordpress.org/Plugin_API ➤ Widgets API: Used to create and maintain widgets in your plugin. The widget will automat- ically appear under the Appearance ➪ Widgets SubPanel and can be used on any defined sidebar on your theme. http://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 auto- matically displays all images uploaded to that post in a gallery style. When editing a post, you

WordPress Codex and Resources ❘ 75 will see the [gallery] shortcode, but viewing it on the public side of your web site displays the actual gallery of images. 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 this API takes the provided URL and tests a series of PHP methods for sending the request. Depending on the hosting environ- ment, 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, Fopen, FSockopen, and HTTP extension. The methods are also checked exactly in that order. You can use the Core Con- trol 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 gen- erate maps and plots. The HTTP API can also easily interact with the Twitter API, allowing you to post/read tweets directly from WordPress. http://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 scrubs all of the setting data saved by the user. This means no more worry- ing 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 each time you needed to save settings in a plugin. http://codex.wordpress.org/Settings_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 screen options hiding. 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. 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.Codex Controversy As with any wiki there will always be controversy over the accuracy of the articles within it and the Codex is no different. One problem that has plagued the Codex is the freshness of the articles. Word- Press 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

76 ❘ CHAPTER 4 TOUR OF THE CORE Codex is a community project, so you can easily create an account and start helping out! We cover contributing to WordPress in Chapter 15. 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 our motiviations for this introduction to the WordPress Core was to pro- vide you with a map to help narrow the scope of your searches and to introduce related functional topics. DON’T HACK 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 upgrade to the latest version of WordPress. Keeping WordPress current is an important step in overall web site security. If any security vulnerability is discovered a patch is typically released very quickly. If you can’t upgrade because you have modified Core files, you are opening up your web site to these security vulnerabilities being exploited and your web site getting hacked. Hacking Core can also lead to an unstable web site 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 Core. WordPress Core is viewed and scrutinized by security experts all over the world. By hacking 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 Core is compassion. That is, compassion toward the developer who comes after you to maintain the web site. Most web sites will change developers over the years so there is no guarantee you will be working on a particular web site five years from now. Imagine the developer that follows you trying to determine what Core files were hacked to make the web site function. This can be a nightmare for any developer and it puts the web site owner in a bad position because most developers will refuse to work on a hacked version of WordPress. If you hack 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 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

Don’t Hack Core! ❘ 77come across a feature we needed that we couldn’t incorporate with a plugin. WordPress is extremelyflexible, which is one of its major strengths, and therefore should never be hacked. Don’t hack Core!If you are fascinated by the WordPress Core and its intricacies, you should join the WordPress Devel-oper Community and get involved fixing bugs and contributing to the Core build of WordPress. We’llcover this in detail in Chapter 15.



5The Loop WHAT’S IN THIS CHAPTER? ➤ Understanding the flow of the Loop and where it can be used ➤ Learning how the Loop determines what content to display ➤ Customizing the Loop with different granularities of data access ➤ Understanding template tags and how they work ➤ Understanding global variables and their relationship to Loop processing ➤ Working outside of the Loop The Loop refers to how WordPress determines what content (posts and pages) to display on a page you are visiting. The Loop can display a single post or page, or a group of posts and pages that are selected and then displayed by looping through the content, thus it’s called the Loop. This is how WordPress displays blog posts by default. The Loop selects posts from the MySQL database based on a set of parameters, and those parameters are typically determined by the URL used to access your WordPress blog. For example, the homepage shows all blog posts in reverse chronological order by default. A category page, accessed via a URL like http://example.com/category/zombies, only shows blog posts assigned to that category, in this case the ‘‘zombies’’ list. An archive page only shows blog posts that are dated with that particular month and year. WordPress maps nearly every parameter about your posts into a selection variable, providing the basis for an equally wide number of different ways to alter the Loop output. It is very easy to customize what content is displayed and where on your web site with a thorough understanding of how the Loop translates a URL into what you see when you access that link. This chapter discusses how the Loop works, where the Loop can be used, and the logical flow of the Loop. It also covers how to customize the Loop using the many different functions and data access methods available in WordPress. Global variables that maintain the current state are also discussed along with working outside of the Loop.

80 ❘ CHAPTER 5 THE LOOP UNDERSTANDING THE LOOP Understanding how the Loop functions will help you understand how you can control it. Controlling the Loop to display exactly the content you want will be one of your most used tools in developing WordPress-powered web sites. Because the Loop is at the heart of every WordPress theme, being able to customize the display content opens up the doors to making WordPress look and act however you want. To understand the Loop, it helps to break down the steps WordPress takes to generate a page’s content: ➤ The URL is matched against existing files and directories in the WordPress installation. If the file is there, it is loaded by the web server. WordPress doesn’t actually get involved in this decision; it’s up to your web server and the .htaccess file created by WordPress to decide if the URL is something handled by the web server or to be turned into a WordPress content query. This was covered in Chapter 4. ➤ If the URL is passed to WordPress, it has to determine what content to load. For example, when visiting a specific tag page like http://example.com/tag/bacon, WordPress will deter- mine that you are viewing a tag and load the appropriate template, select the posts saved with that tag, and generate the output for the tag page. ➤ The translation of URL to content selection magic happens inside of the parse_query() method within the WP_Query object that WordPress created early on in its processing. WordPress parses the URL first into a set of query parameters that are described in the next section. All query strings from the URL are passed into WordPress to determine what content to display, even if they look like nicely formatted pathnames. If your site is using pretty permalinks, the values between slashes in those permalinks are merely parameters for query strings. For example, http://example.com/tag/bacon is the same as http://example.com?tag=bacon, which conveys a query string of ‘‘tag with a value of bacon.’’ ➤ WordPress then converts the query specification parameters into a MySQL database query to retrieve the content. The workhorse here is the get_ posts() method within the WP_Query object that we describe later in this chapter. The get_ posts() method takes all of those query parameters and turns them into SQL statements, eventually invoking the SQL string on the MySQL database server and extracting the desired content. The content returned from the database is then saved in the WP_Query object to be used in the WordPress Loop and cached to speed up other references to the same posts made before another database query is executed. ➤ Once the content is retrieved, WordPress sets all of the is_ conditional tags such as is_home and is_ page. These are set as part of executing the default query based on the URL parsing, and we’ll discuss cases where you may need to reset these tags. ➤ WordPress picks a template from your theme based on the type of query and the number of posts returned, for example, a single post or a category only query, and the output of the query is passed to this default invocation of the Loop. The Loop can be customized for different web site purposes. For example, a news site might use the Loop to display the latest news headlines. A business directory could use the Loop to display local businesses alphabetically by name, or always put posts about sponsoring businesses at the top of every

Flow of the Loop ❘ 81displayed page. A photo blog might use the Loop to display the most recent photos loaded into theweb site. The possibilities are endless when customizing the Loop in WordPress because it gives youcomplete control over what content is selected and the order in which it is rendered for display.PUTTING THE LOOP IN CONTEXT Header Sidebar The Loop is the heart of a theme, which is what controls how your content is displayed. It is the functional connection between the MySQL database data and the HTML that is rendered in the visitor’s browser. Basically anywhere a post or page is displayed, WordPress is going to use the Loop. This can be a single post or page, a loop of posts, or a sequence of loops with different display options.Most WordPress themes feature a header, footer, and sidebar The WordPress Loopelement. Figure 5-1 shows how the Loop is placed directly in the Footermiddle of these elements, creating your web site content area. Thissection of your web site is usually dynamic and will change as you FIGURE 5-1: The WordPress Loopnavigate through it. HeaderThe Loop by default is used in your WordPress theme template Sidebarfiles. Custom Loops can be created anywhere in your theme tem-plate files, as Figure 5-2 shows. Custom Loops are also usedin plugins and widgets. Loops can be used anywhere inside ofWordPress, but different methods exist for creating custom Loopsdepending on where they are used, and the potential side effectsof each construction will differ.Multiple Loops can be used throughout your theme template files.Custom Loops can be created in your header, sidebars, footer,and main content areas of your web site. There is no limit to thenumber of Loops that can be displayed on your web site.The following section looks at the basic flow control of the Loop, Footerand the WordPress template functions provided to customize theway content is displayed while being handled inside of a loop.Armed with the basics, it then goes into building custom loopsbased on hand-tailoring those query parameters.FLOW OF THE LOOP FIGURE 5-2: Using multiple LoopsThe Loop uses some standard programming conditional statements to determine what and how todisplay. The first statement in the Loop is an if statement, checking whether any posts exist, becauseyou might not have any posts with the specified category or tag. If content exists, the while statementis used to initiate the Loop and cycle through all posts or pages that need to be displayed. Finally,the_ post() function is called to build the post data, making it accessible to other WordPress functions.Once the post data has been built, Loop content can be displayed in whatever format you like.

82 ❘ CHAPTER 5 THE LOOP Following is a minimal Loop example. This example features the only required elements for the Loop to function properly: <?php if (have_ posts()) : while (have_ posts()) : the_ post(); //loop content (template tags, html, etc) endwhile; endif; ?> Remember that this is PHP code, so it needs to be surrounded in <?php and ?> tags. This is the Loop in its simplest form. If you’re wondering how the output from the database query got handed to this simple Loop when there are no variables passed as parameters, the answer lies in the global variable $wp_query, which is an instance of WP_Query that is referenced by the functions in the simple Loop. It is in effect the ‘‘default query’’ for the Loop. Note that by the time this default Loop is called, WordPress has already called the get_ posts()method within the default query object to build the list of appro- priate content for the URL being viewed, and the Loop in this case is charged with displaying that list of posts. Later on, you look at how to hand-structure queries to exercise fine-grain control over post selection, but for now it’s safe to assume that the database heavy lifting has been done, and the results are stored in $wp_query, when the Loop is invoked. Some very minimal requirements exist for the Loop to work in WordPress. Let’s break down this example to look at the different parts of the Loop: if (have_ posts()) : This line checks if any posts or pages are going to be displayed on the current page you are viewing. If posts or pages exist the next line will execute: while (have_ posts()) : The preceding while statement starts the Loop, essentially looping through all posts and pages to be displayed on the page until there are no more. The Loop will continue while content exists to be displayed. Once all content has been displayed the while loop will end. The have_ posts() function simply checks to see if the list of posts being processed is exhausted, or had no entries to begin with. the_ post(); Next, the the_ post() function is called to load all of the post data. This function must be called inside your loop for the post data to be set correctly. Calling the_ post() in turn calls the setup_ postdata() function to set up the per-post metadata such as the author and tags of the content you are displaying in the Loop, as well as the content of the post itself. This data is assigned to a global variable each time through the Loop iteration. Specifically calling the_ post() has the side effect of setting up the global $post variable used by most of the template tags described later on, and then advances to the next post in the list. Setting up the post data also applies the appropriate filters to the raw content that comes out of the WordPress database. WordPress stores user-edited content exactly as entered, so if a user adds a

Flow of the Loop ❘ 83shortcode, for example, to add a Google AdSense item at the end of a post, the shortcode is stored inthe database content. When the post setup is done, the plugin that converts that shortcode to a chunkof JavaScript is called, along with other registered plugins that modify the raw post content. We’ll lookat the plugin mechanics in Chapter 7, but for now, it’s important to note the distinction between theraw post data in the WordPress query object and the filtered content that is eventually rendered. //loop contentThis is where all Loop template tags are placed and any additional code you want displayed inside theLoop. We cover this in more detail further along in this chapter. endwhile; endif;The endwhile and endif calls end the Loop. Any code placed after these two lines will show at thebottom of your page, after all posts have been displayed. You could also place an else clause to displaya message if there is no content to display in the Loop.The Loop is usually surrounded by HTML tags in your theme template files. The following code showshow the Loop is structured in the default Kubrick theme that comes with WordPress: <div id=\"content\" class=\"narrowcolumn\" role=\"main\"> <?php if (have_ posts()) : ?> <?php while (have_ posts()) : the_ post(); ?> <div <?php post_class() ?> id=\"post-<?php the_ID(); ?>\"> <h2><a href=\"<?php the_ permalink() ?>\" rel=\"bookmark\" title=\"Permanent Link to <?php the_title_attribute(); ?>\"><?php the_title(); ?></a></h2> <small><?php the_time(’F jS, Y’) ?> <!-- by <?php the_author() ?> --></small> <div class=\"entry\"> <?php the_content(’Read the rest of this entry &raquo;’); ?> </div> <p class=\"postmetadata\"><?php the_tags(’Tags: ‘, ‘, ‘, ‘<br />’); ?> Posted in <?php the_category(’, ‘) ?> | <?php edit_ post_link(’Edit’, ‘’, ‘ | ‘); ?> <?php comments_ popup_link(’No Comments &#187;’, ‘1 Comment &#187;’, ’% Comments &#187;’); ?></p> </div> <?php endwhile; ?> <div class=\"navigation\"> <div class=\"alignleft\"><?php next_ posts_link(’&laquo; Older Entries’) ?></div> <div class=\"alignright\"><?php previous_ posts_link(’Newer Entries &raquo;’) ?> </div> </div> <?php else : ?>

84 ❘ CHAPTER 5 THE LOOP <h2 class=\"center\">Not Found</h2> <p class=\"center\">Sorry, but you are looking for something that isn’t here.</p> <?php get_search_form(); ?> <?php endif; ?> </div> Notice how the minimal Loop elements exist, but are surrounded by HTML tags. This is how a normal theme template file will be structured to utilize the Loop. The HTML elements can certainly change, but the Loop elements stay the same. Customizing the style in which content is displayed and choosing post metadata to include in the page composition is done through template tags. TEMPLATE TAGS PHP functions used in your WordPress theme templates to display Loop content are called template tags. These tags are used to display specific pieces of data about your web site and content. This allows you to customize how and where content is displayed on your web site. For example, the the_title() template tag displays the title of your post or page inside the Loop. The major benefit of using template tags is that you don’t need to know PHP code to use them. Many different template tags are available in WordPress. Some template tags must be inside the Loop, whereas other tags can be used anywhere in your theme template files. Note that in this context, tem- plate tags refer to the WordPress functions used to extract post data for display; template files are the theme elements that control how content for a particular content type is displayed. Put another way, template files contain Loops comprising template tags. For an updated list of template tags available in WordPress visit http://codex.wordpress.org/Template_Tags. Commonly Used Template Tags There is no shortage of template tags, but typically you will use only a handful of tags in your Loops. Following are the most commonly used template tags available in the Loop. These template tags will return and display the post data listed. ➤ the_ permalink(): Returns the URL of your post. ➤ the_title(): Returns the title of the post. ➤ the_ID(): Returns the unique ID of your post. ➤ the_content(): Returns the full content of your post. ➤ the_excerpt(): Returns just an excerpt of your post. If the Excerpt field is filled out on the Post edit screen, that will be used. If not WordPress will auto-generate a short excerpt from your post content.

Template Tags ❘ 85 ➤ the_time(): Returns the date/time your post was published. ➤ the_author(): Returns the author of the post. ➤ the_tags(): Returns the tags attached to the post. ➤ the_category(): Returns the categories assigned to the post. ➤ edit_ post_link(): Displays an ‘‘edit’’ link that is shown only if you are logged in and allowed to edit the post. ➤ comments_ popup_link(): Displays a link to the comments form of your post. To learn how template tags work, just place any template tag inside the Loop and view the results. The following example views the values of a couple different template tags: <?php if (have_ posts()) : while (have_ posts()) : the_ post(); ?> <a href=\"<?php the_ permalink(); ?>\"><?php the_title(); ?></a> <br> <?php the_content(); endwhile; endif; ?> As you can see your post titles are displayed with links to the permalink for each post. The content of the post is displayed directly below the post title.Tag Parameters Most template tags have parameters that can be added to modify the value returned. For example, the the_content() template tag has three parameters. The first parameter allows you to set the ‘‘more’’ link text like so: <?php the_content(’Read more’, False); ?> Your post content will be displayed as normal, but when the <!--more--> tag is found in your post, WordPress will automatically add the text ‘‘Read more,’’ which would link to the entire blog post. The second parameter determines whether to display the teaser paragraph again when viewing the full post. The default value is False so the teaser will be displayed in both places. The More tag in WordPress allows you to display a defined teaser from the full post on your web site. For example, you could display the first paragraph of a post on your homepage, and only show the full blog post when a visitor clicks the link to view the full post. To accomplish this you can place <!--more--> in your content in HTML view where you want this break to happen. In the visual editor there is a button to insert a More tag.

86 ❘ CHAPTER 5 THE LOOP You can also send multiple parameters to any tag that supports it. For example, the template tag the_title() accepts three parameters: $before, $after, and $echo. The following code sets the the_title() tag’s $before and $after parameters to wrap the post title with h1 tags: <?php the_title(’<h1>’, ‘</h1>’); ?> You can also view the actual function in the WordPress source code. The post template func- tions are located in wp-includes/post-template.php. Doing a quick search for ‘‘function the_title()’’ will lead you to the exact function for the the_title() tag. You can also use the Codex for a detailed description of the template tag you are working with, in this case http://codex.wordpress.org/Template_Tags/the_title. CUSTOMIZING THE LOOP In our opening discussion of Loop flow of control, we mentioned that the main workhorse for data selection is the get_ posts()method of the WP_Query object. In most cases, if you want to build a custom Loop, you’ll build your own WP_Query object and reference it explicitly. Alternatively, you can use the lower-level query_ posts() and get_ posts() functions (not to be confused with the methods within the WP_query object of the same name) to manipulate the output of the default query that was passed into your Loop. Both query_ posts and get_ posts use the WP_Query class to retrieve content. We’ll look at the lower level approaches and discuss how and where you should — and shouldn’t — use them, but we’ll start with a discussion of how you build a custom query object. Using the WP_Query Object Once WordPress is handed a URL to parse by the web server, it goes to work disassembling the tokens in that URL and converting them into parameters for a database query. Here’s a bit more detail on what happens when manipulating your own WP_Query. WP_Query is a class defined in WordPress that makes it easy to create your own custom Loops. Both query_ posts and get_ posts use the WP_Query class to retrieve the WordPress content. When you’re using query_ posts() the global variable $wp_query is used as an instance of WP_Query, making $wp_query the default data store for several operations. Custom Loops can be used anywhere in your theme template files to display different types of content; they must build on separate instances of a WP_Query variable. When you create a new WP_Query object, it’s instantiated with some default functions for building queries, executing the query to get posts, and parsing parameters out of a URL. However, you can use these built-in object methods to construct your own parameter strings, creating custom loops that extract whatever particular content you need for that point in your Loop. The following is an example of a custom Loop displaying the five most recent posts on your web site: <?php $myPosts = new WP_Query(); $myPosts->query(’posts_ per_ page=5’); while ($myPosts->have_ posts()) : $myPosts->the_ post(); ?> <!-- do something --> <?php endwhile; ?>

Customizing the Loop ❘ 87 Rather than using the simpler have_ posts() and the_ post() calls that we saw in the basic Loop, this custom loop calls the methods of the newly created WP_Query object myPosts. The explicit invocation shown here and the default have_ posts() call are functionally equivalent; have_ posts() for example is merely calling $wp_query->have_ posts() using the global query variable for the default query, that is, the one generated from parsing the URL handed to WordPress by the web server. Going into your default Loop from the URL used to invoke WordPress, there’s an additional step that takes the URL and parses it into an appropriate query string using the parse_query() method of the query object. When you build your own custom Loop, you explicitly set the parameters you want to control the query. Here’s a bit more detail on what happens inside the query function: ➤ Calling $myPosts->query() converts the parameters into a SQL statement via the function $myPosts->get_ posts(), which then executes the query against the MySQL database and extracts the content you’ve requested. ➤ Equally important, the query call sets up the conditional tags such as is_home() and is_single() that are dependent upon the type of page displayed and the quantity of content for that page. ➤ The array of posts returned by the query is cached by WordPress so that future references to the same query won’t generate additional database traffic. The key to building a powerful custom Loop is to map your content selection criteria into the right set of query parameters.Building A Custom Query Parameters are used to define what content will be returned in your Loop, whether a custom Loop or altering the primary Loop. When creating Loops it’s essential to understand what parameters are avail- able to help define what content will be displayed. You can use many different, sometimes confusing, parameters in creating your custom Loop to alter the output of your content. Multiple parameters can also be set per query by separating the parameter name and values with an ampersand. For a detailed list of available parameters, visit http://codex.wordpress.org/ Template_Tags/query_ posts#Parameters. Following are some of the more commonly used parameters.Post Parameters The most obvious, and sometimes most used parameters, select the number and types of posts to be displayed: ➤ p=2: Loads an individual post by ID. ➤ name=my-slug: Loads post based on post slug (permalink tail). ➤ post_status=pending: Loads posts by post status. For example, if you choose to only see drafts, use post_status=draft . ➤ caller_ get_ posts=1: Excludes sticky posts from being returned first. A ‘‘sticky post’’ is one that always sorts to the head of the list of posts, independent of the other parameters set for






























































Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook