WordPress Development Tutorials

How to get post content in WordPress with WP Query and the loop

Pinterest LinkedIn Tumblr

The Loop refers to how WordPress determines what content (posts, pages, or custom content) to display on a page you are visiting. The Loop can display a single piece of content or a group of posts and pages that are selected and then displayed by looping through the content; thus, it’s called the Loop.

Following is a minimal Loop example.

<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
//loop content (template tags, html, etc) endwhile;
endif; ?>

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.

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 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.

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 appropriate content for the URL being viewed, and the Loop in this case is charged with displaying that list of posts.

The Loop is usually surrounded by HTML tags in your theme template files. The following code shows how the Loop is structured in the core Twenty Fourteen theme that comes with WordPress:

<div id="main-content" class="main-content">
<?php
if ( is_front_page() && twentyfourteen_has_featured_posts() ) {
// Include the featured content template.
get_template_part( 'featured-content' ); }
?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php
if ( have_posts() ) :
// Start the Loop.
while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile;
// Previous/next post navigation. 
twentyfourteen_paging_nav();
else :
// If no content, include the "No posts found" template. 
get_template_part( 'content', 'none' );
endif; ?>
</div></div>
<?php get_sidebar( 'content' ); ?>
</div>

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 website and content. This allows you to customize how and where content is displayed on your website.

Commonly used template tags

  • the_permalink(): Displays the URL of your post.
  • the_title(): Displays the title of the post.
  • the_ID(): Displays the unique ID of your post.
  • the_content(): Displays the full content of your post.
  • the_excerpt(): Displays the 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.
  • the_time(): Displays the date/time your post was published.
  • the_author(): Displays the author of the post.
  • the_tags(): Displays the tags attached to the post.
  • the_category(): Displays 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.
  • comment_form(): Displays a complete commenting form for your post.

The following example views the values of a couple of 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;
?>

Using the WP_Query Object

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.

The following is an example of a custom Loop displaying the five most recent posts on your website:

<?php
$myPosts = new WP_Query( 'posts_per_page=5' );
while ( $myPosts- >have_posts() ): 
$myPosts->the_post();
?>
<?php endwhile; ?>

Post Parameters

Parameters are used to define what content will be returned in your Loop, whether a custom Loop or altering the primary Loop

  • p=2: Loads an individual post by ID.
    name=your-slug: Loads posts based on post slug (permalink tail).
  • post_status=pending: Loads posts by post status. For example, if you choose to see only drafts, use post_status=draft.
  • ignore_sticky_posts: Excludes sticky posts from being returned first. A sticky post is one that always sorts to the top of the list of posts, independent of the other parameters set for the query. You can have multiple sticky posts, making them useful for calling attention to news announcements, highlighting changes, or otherwise grabbing the reader’s attention, and this parameter lets you drop them from their priority slot at the top of the list.
  • post_type=post: Loads posts based on type. If you only want to look at pages, not posts, post_type=page will retrieve them.
  • posts_per_page=5: Number of posts to load per page. This is the default. To show all posts, set this parameter to 1.
  • offset=1: Number of posts to skip before loading

Page parameters

  • page_id=5: Loads an individual page by ID. Like post IDs and user IDs, page IDs can be found in the dashboard by hovering over a page and looking at the URL displayed at the bottom on your browser.
  • pagename=Contact: Loads a page by name, in this case the Contact page.
  • pagename=parent/child: Loads a child page by slug, or hierarchy of slugs (that is, its path)

Category, Tag, and Author Parameters

  • cat=3,4,5: Loads posts based on category ID.
  • category_name: About Us: Loads posts based on category name. Note that if a post belongs to more than one category, it will show up in selections for each of those categories.
  • tag=writing: Loads posts based on tag name.
  • tag_id=34: Loads posts based on tag ID.
  • author=1: Loads posts based on user ID.
  • author_name=brad: Loads posts based on author’s name. author__in & author__not_in ”Loads posts based on user ID

Ordering and Custom Field Parameters

  • orderby=title: Field to order posts by.
  • order=ASC: Defines ascending or descending order of orderby.
  • meta_key=color: Loads posts by custom field name.
  • meta_value=blue: Loads posts by custom field value. Must be used in conjunction with the meta_key parameter.
  • meta_query: Used for more advanced custom field (metadata) queries.

Adding Paging to a Loop

<?php
$temp = $wp_query;
$wp_query= null;
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; 
$wp_query = new WP_Query( 'posts_per_page=5&paged='.$paged );
while($wp_query->have_posts() ) : $wp_query->the_post();?>
 <h2>
   <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> 
 </h2>
<?php the_excerpt(); ?>
endwhile; ?>

<div class="navigation">
<div class="alignleft"><?php previous_posts_link( '« Previous' );
?></div>
<div class="alignright"><?php next_posts_link( 'More »' ); ?></div>
</div>
<?php
$wp_query = null;
$wp_query = $temp; 
?>

First, you have to store the original $wp _ query variable into the temporary variable $temp. Next, you set $wp _ query to null to completely flush it clean. This is one of the few times it’s acceptable to overwrite a global variable value in WordPress.

Now set your new WP _ Query object into the $wp _ query variable and execute it by calling the object’s query() function to select posts for your custom Loop. Notice the $paged variable added to the end of the query. This stores the current page, using the get _ query _ var() function, so WordPress knows how to display the navigation links.

I'm a full stack developer. I have experiences with Java, Android, PHP, Python, C#, Web development...I hope website https://learncode24h.com will help everyone can learn code within 24h and apply it in working easily.

Write A Comment