A Practical Use of WordPress Global Variables

In the first article in this series, we reviewed an introduction to WordPress global variables. Specifically, we said that they are variables that hold a variety information that can be accessed from anywhere in the WordPress page lifecycle.

We learned how to access a global variable and display various details about the latest post using the $post global variable. In today’s article, we will dive further into global variables by learning how to access them to display the author information.

Retrieving Author Data

Most information about the author of the given post or pages are available through the global variable $authordata.  To get started with the $authordata global cariable we need to use the following snippet:

Next, let's edit the page.php of the twentyfourteen theme and insert the above snippet right after the get_template_part(‘content’, ‘page’) which fetches the content and displays it on the page.  

We should have the following code in the page template now:

When we save the page.php and access an existing WordPress page we should be able to see the following result:

Authordatapng

We could thus access each of the individual values of the above object as follows:

The above snippet would print the display name of the author who wrote the page. Similarly you could try writing a code snippet that would display the other values of the $authordata such as the author username, author email, etc. 

Remember that we could use the $authordata in powerful ways in our theme and plugin development to perform various functions.

Let us perform a hands on activity with the $authordata global variable to get the list of the three latest posts of the author and display the posts as links. This will require the following steps:

First, add the function to fetch and display three posts by the author in functions.php

  • First, we declare that we are accessing the global variables $authordata and $post. We proceed to use get_posts WordPress template tag to fetch three posts by the current author and store it in an array called $author_three_posts.
  • Secondly, we loop through the $author_three_posts array using a foreach loop to print the title of the post that links to the actual post, here we use the get_permalink and get_the_title to fetch the link and the title from the post ID.
  • Finally, we return the printed value as a variable called $output.

Next, call the tutsplus_display_three_posts() function name to be executed in the single.php of the twentyfourteen theme:

After that, open a single post page to test the execution of our code:

LatestPostspng

Wrapping It Up

With that we conclude the second part of the series. As you can see from the above example, it is possible to use the global variables to perform simple operations to complex functions within WordPress development.

References

Tags:

Comments

Related Articles