post-page

Global Variables and the WordPress Loop

40
responses
by
 
on
June 6th, 2007
in
WordPress FAQs, WordPress Tips

My name is Ronald Huereca and am a new author here at WLTC. I come from a technical and business background with a degree in EET and a MS in Business Administration. I hope to share with the WTLC readers some of little intricacies of WordPress, whether it be theme or plugin related. I have written a few plugins, one called Feed Styler and the other Ajax Edit Comments. I currently write for my personal blog, the Reader Appreciation Project, and Devlounge. I am open to any and all feedback, so if there is something you’d like to see me write about, please let me know.

When coding a WordPress plugin, one thing that must be quickly mastered is that of the WordPress loop and global variables. Once mastered, a plugin author can tell which global variables are accessible, and which are not.

With certain WordPress Action and Filters, it’s easier to tell where within the loop certain code is executed. Sometimes, however, you don’t want to use an action or filter and want to simply have a template tag that is called from within the loop. When doing this, you want to make sure you know exactly what global variables you are trying to access and what result you’d like to achieve.

Within this post, I will dissect the WordPress loop so that you might have a better understanding of what variables are available to be called by template tags of functions called from within the WordPress loop.

The WordPress Loop

The WordPress loop is the loop that displays the posts on a particular page and also the comments if on a single post.

WordPress Loop Diagram

Within your default index.php theme file, the loop begins when you see this code:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

The two functions have_posts() and the_post() are both property functions that access methods within the WP_Query class.

The have_posts function checks to see if the current post number is less than the number of posts you choose to display in the Admin panel. The loop will then continue until the current post number reachers the maximum number of posts you have decided to show.

If you were to dissect the_post function, you would find that it searches for the global variable $post. The the_post function gets the first post (and subsequent posts through each loop iteration), and sets up the post data (author, multi-page, etc). This data is assigned to the $post variable globally, so you may access it as well.

After the_post() has been called, you have access to a multitude of template tags and global variables. Below are some examples of template tags that are now available:

  • the_author: Retrieves the author’s name.
  • the_title: Displays the title of the current post.
  • the_content: Displays the contents of the post.
  • the_permalink: Displays the URL for the post in the form of a permalink.
  • the_ID:Displays the post ID.

Listed below are the global variable equivalents of each of those template tags:

  • Global variable authordata can be used. You could call it in a function using this code:

    global $authordata;
    echo $authordata->display_name;

    The authordata global can also access: nickname, last_name, first_name, ID, user_email, user_url, user_login, description, and several others.

  • Global variable post can be used. You could call it in a function using this code:

    global $post;
    echo $post->post_title;

    The post global can also access: ID, post_author, post_date, post_excerpt, comment_count, and several others.

  • Global variable post can be used. You could call it in a function using this code:

    global $post;
    echo $post->post_content;

    Keep in mind that accessing the content this way is accessing the unfiltered and untouched post content. This is useful if you wanted to manipulate the content to your liking instead of WordPress having a say in the content appearance.

  • There is no quick global access, but all the_permalink function does is echo out the results of the function get_permalink with the assumption that the $id variable is set.
  • Global variable id can be used. You could call it in a function using this code:

    global $id;
    echo $id;

A Template Tag Example

Say you made a custom template tag called get_my_trackback that was to do something everytime a trackback was detected within the comments loop. You would place the function call within the foreach comments loop in the comments.php template file. This example assumes that you are on a single post using the single.php template file.

<?php foreach ($comments as $comment) : ?>
get_my_trackback();
<?php endforeach; /* end for each comment */ ?>

Within this get_my_trackback function, you can do something like:

function get_my_trackback() {
global $comment;
if (empty($comment)) { return; }
if ($comment->comment_type != 'comment') {
//do trackback stuff
}
}

WordPress Comments Loop Diagram

The comment global allows you to access the comment database fields so you can do just about anything regarding the comment. Please notice that the global variable is not assumed to be set. You always want to make sure the variable has a value before proceeding so that errors are minimal.

Conclusion

Within this post the WordPress loop was dissected and global variables explained so that you may access them from a template tag in an include file or a WordPress plugin. If you have any questions, comments, or additions, please feel free to weigh in.

heading
heading
40
Responses

 

Comments

  1. AJ says:

    Congrats on becoming an author here Ron! Hopefully more people will be able to benefit from your WP knowledge 🙂

  2. *EXCELLENT POST*! Thanks!

  3. jez says:

    great article, I am looking forward to reading more from your side. also I like the fancy illustrations:)

  4. steve says:

    Excellent post! Great info..

    Just installed the Ajax Edit Comments WP Plugin actually – great upgrade.

    Thanks,

    –Steve

  5. rkcorp says:

    i can’t believe i manage to take some time to read it in full..:)
    Great stuff man…yes..custom template tag is definately useful if you don’t want to clutter your theme code..for easy plugin intergration..all the plugin yo developed are superb…pingback and default comment separated also sure come handy..

    there is one custom template tag i would like to see..something like a post feature..ye know let’s say i only want my latest post in category A to be in top of my frontpage…and if i post latest post in category B..it will not replace the first post from category A..:)

    sure appreciate it if someone have similiar custom template tag without using plugin..thanks.

  6. Ronald says:

    Thanks for all the feedback. Template tags do some in handy for organizing theme code.

  7. Bryce says:

    Thanks heaps, this is a really useful tutorial.

  8. Sudar says:

    Thanks for the tutorial. It has cleared up lot of confusion which I had over the LOOP. It is a great source for plugin authors like me. Thanks 🙂

    Cheers,
    Sudar

  9. Micha says:

    Thanks for the good explanation! It was usefull for me to get into WP loops.

  10. holy hannah says:

    Hi, this is all like reading a foreign language to me so forgive me if I’m completely in the wrong area. I’m looking for a way to get a list of all the blogs by a writer automatically listed on their individual bio page. Sort of a personal archive for each writer. Is this plugin loop something that would work for that?
    Thanks

  11. ChrisM says:

    I think your subscribe to comments plugin is misbehaving…
    I left a comment on the New Twist on Premium WordPress Themes post, and am now receiving new comment notifications on this and Printer Friendly Codex posts…

  12. ben says:

    can you tell me what is the code for gettin a post category and parent category links like in the top of that post?

  13. Very nice article.. I really wanted to know about all the global variables supported by wordpress, specially related to the comments section ^_^ Thanks for the share..

  14. Mick says:

    Thanks for the post – was struggling getting my head round how the loop worked but your diagrams helped a lot.



Trackbacks/Pingbacks

  1. […] Source:Weblog Tools Collection My name is Ronald Huereca and am a new author here at WLTC. I come from a technical and business background with a degree in EET and a MS in Business Administration. I hope to share with the WTLC readers some of little intricacies of WordPress, whether it be theme or plugin related. […] Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages. […]

  2. […] Global Variables and the Loop – An in-depth explanation. […]

  3. […] Simple pero preciso. Aprende cómo funciona WP. Vía Blogpocket Artículos relacionados :Posible contrataque de NintendoCómo hacer nudosMovistar, AvísaMe, ¡por favor!Manual para crear un plugin para WP para torpesWordpress para Wii Clasificado bajo:Weblogs / How to / minipost Comentarios : […]

  4. […] Aprende como es que funciona WordPress, si no sabes que es wordpress, es probablemente el mejor software para la creación de blogs que además es de código abierto y que usamos actualmente en Estrafalarius. En: WordPress, Mini-Posts — June 6, 2007 […]

  5. […]   Global Variables and the WordPress Loop,讲述WordPress在模板中如何处理全局变量和回环处理,对于模板作者们来说这是一篇很不错的结构文章。 […]

  6. […] Global Variables and the WordPress Loop Simple pero preciso post sobre la logica interna de funcionamiento de WordPress. (tags: Blogs WordPress) […]

  7. […] Huereca from WLTC wrote a very informative blog post on the WordPress loop and global variables. In the post he discusses a series of programming […]

  8. […] Weblog Tools Collection » Blog Archive » Global Variables and the WordPress Loop […]

  9. […] Global Variables and the WordPress LoopVery detailed description of the WordPress Loop, and the globals available within. […]

  10. […] Aprende cómo funciona WordPress en Weblog Tools Collection un sencillo artículo sobre las variables globales en Wordress y los loops. […]

  11. […] Weblog Tools Collection » Blog Archive » Global Variables and the WordPress Loop (tags: wordpress programming plugins php) […]

  12. […] blog, general i dearly wanted 2 know the wordpress stuff.. here it is and it’s informative >> No Comments so far Leave a comment RSS feed for comments on this post. TrackBack URI […]

  13. […] Weblog Tools Collection » Blog Archive » Global Variables and the WordPress Loop (tags: wordpress webdev programming) […]

  14. […] funciona WordPress? Una muy buena explicación de como funciona nuestro CMS […]

  15. […] Great tips from the gold standard wordpress blog […]

  16. […] ????Global Variables and the WordPress Loop????????Ronald Huereca ? Ajax Edit Comments ? Feed Styler ???????????????????????????????? ?????????? WordPress ???? ???????????????????????????????????? ?????????????? ? ??????????? ? […]

  17. […] Guide to the WordPress Loop: Ah, the famed WordPress loop that runs it all. Ronald has done a very nice job of identifying global variables in the WordPress loop in the past. Much like that post, this guide is for themers and plugin developers who want the […]

  18. […] Anyway, two recent articles, I have have found helpful are: The Ultimate Guide to the WordPress Loop and another called Global Variables and the WordPress Loop. […]

  19. […] Thanks for visiting! If you’re new here, you may want to subscribe to our RSS feed. This blog posts regular WordPress news, updates of themes, plugins, ideas, hacks, quick fixes and everything about blogging, especially about WordPress. Go ahead, subscribe to our feed! You can also receive updates from this blog via email.We all know what the WordPress Loop is right? If not, there are many great tutorials around the web that explain the WordPress Loop. […]

  20. […] Weblog Tools Collection » Blog Archive » Global Variables and the WordPress Loop Ähum, wordpressloopen verkar vara nån basicgrej. (tags: wordpress loop) […]

  21. […] Weblog Tools Collection » Blog Archive » Global Variables and the WordPress Loop […]

  22. […] Link: Weblog Tools Collection […]

  23. […] many great tutorials around the web that explain the WordPress Loop. […]

  24. […] We all know what the WordPress Loop is right? If not, there are many great tutorials around the web that explain the WordPress Loop. […]

  25. […] Notice the use of the recentPosts variable to start the loop. We utilize two methods of WP_Query, which is have_posts and the_post. You can read more about those two methods on my article Global Variables and the WordPress Loop. […]

  26. […] know what the WordPress Loop or query_posts(). If you have no clue what that is, then you should read more about it because it’s kind of a big deal, and very important to know if you plan to develop with […]

Obviously Powered by WordPress. © 2003-2013

css.php