ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Wordpress & PHP Tutorial: Printing Messages Dynamically Based off of the Post Category

Updated on June 9, 2009

The purpose of this tutorial is to show how to print special messages on a Wordpress post, depending on the posts category.

Using PHP, it is possible to show a specific message to visitors of posts, where the message is different for each category.

What?

For example, say you had a blog that describes different types of music.

On each of your posts, you might have a message that requests the user to subscribe to your RSS feed. This message might say “If you enjoyed this post, please subscribe to my RSS Feed.”

By using the method I am about to describe, you could show a slightly different and more personalized message for each of your different categories.

So, instead of printing the same thing on every page, you could say “If you enjoyed this Country Music post, please subscribe to my RSS Feed.” on your Country Music Posts and change this depending on what type of music is used.

This function could also be used to dynamically print/execute different php, javascript, or html on posts depending on the category.

Required Knowledge

This tutorial requires some knowledge of PHP and Wordpress. I will try to describe how everything works, but understanding a little programming language will be important.

We will be declaring variables, using built in Wordpress Functions, working with Arrays, using IF/Else statements, and searching to see if a string contains another string.

Important Disclaimer

It is important to note that editing your Wordpress Theme can temporarily break your Site. It is important to make a back up of any files you edit first and if you have a high traffic site, you might not want to mess with it during peak traffic times.

Since if your theme were to break, you might not be able to use Wordpress Built-in Web Interface, this tutorial assumes you are using SSH and VIM to edit your themes files, or at least know how in the event that something breaks.

If you don't know how to use SSH and VIM with your web host, it might not be a good idea to make too many changes to your theme, because if something breaks you might not be able to fix it.

***You can do everything in this tutorial by using Wordpress's built in Theme Editor, but again if you do this and something breaks, you might not be able to access the Theme Editor until you fix the error unless you SSH into your server and use VIM.***

The Code

If you are anything like me, you like to see the code first and learn by example.

However before you do anything, SSH into your host and backup your theme. Then, using VIM, which is a command line text editor, we will edit your themes functions.php file.

Most themes have a functions.php file, but if not you can make the file by using the command “touch functions.php”

Below, you will see a sample funtions.php file and the showCode function.

Lines #1 and #21 should only appear ONCE in a functions.php file! They should be located at the top and bottom of the page respectively.

<?php

function showCode()
{
   $search = "country";
   $category = get_the_category();

   if( stristr($category[0]->cat_name,$search))
    {
      echo "This is a Country Post!";

    }
    else
    {
       echo "This is NOT a Country Post!";

    }

}

?>

An Explanation of the showCode() Function

Line # 3: Declares the Show Code Function. Note that it does not take any parameters.

Line # 5: Decleres the search variable. This is what we are searching for, in this case Country Music. You can change this to the name of the category that you want to change.

Line # 6: Declares the category variable and uses Wordpress's built in get_the_category(); function. The get_the_category() function returns an array of the posts different categories.

Doing the Actual Work

The next part, Lines 8 -17, is where all the work gets done and might not be as straightforward as the others, so I decided to give this part its own section. We use an if/else statement to search the name of the category.

Line 8: This line uses an if statement and searches the posts category to see if it contains the search variable. Since get_the_category() returns and array of the pages category, we specifically look at the pages first category.

Specifically, the statement $category[0]->cat_name returns the name of the first category.

The stristr() function is a php function that among other things, searches a string to see if it contains another string. It is important to note that the stristr() function is NOT case sensitive, meaning that it treats uppercase and lowercase letters the same. If you wanted to do a case sensitive search, you could use strstr() instead.

So, the statement stristr($category[0]->cat_name,$search) means Does the post category contain the $search variable?

Lines 9 - 12: If the post category does contain the $search variable, then it will print the message “This is a Country Post!” using the echo command.

You can change Line# 10 to whatever code or special message you want to print, but rember if you use special characters, like quotation marks, they need to be escaped first. You do of course have to keep the echo statement and only change the part in between the quotes.

Lines 13 - 17: If the post category does not contain the $search variable than the else statement will be executed, printing "This is NOT a Country Post!"

You can change Line# 15 to whatever code or special message you want to print, but rember if you use special characters, like quotation marks, they need to be escaped first. You do of course have to keep the echo statement and only change the part in between the quotes.

Using the showCode() Function

Once you have the function in place, you can just call the showCode() function whenever you want to print your special message.

For example, you could add the showCode() function to the top of single.php, which is the file that is used to display a post on wordpress. You could also add it to sidebar.php, footer.php, or any of the other theme files which is the file that prints your side bar. However, please note that if you put in on a file, such as footer.php that always gets used on pages, posts, and the main index page, then your special messag might also always be called.

Just add the following line whenever you want to display your special message:

<?php showCode(); ?>

Final Notes

Before you do anything, make sure you read the disclaimer, but if you have any questions, please do not hesitate to ask and I will try to help you out.

I used an if/else statement for simplicity, not sure how simple it is though ;), but you could also use an if/elseif/else statement to check for different categories.

I have included a slightly more advanced showCode() function below, which checks multiple categories.

showCode() for Multiple Categories

<?php

function showCode()
{
   $firstSearchCategory = "country";
   $secondSearchCategory = "rock";
   $category = get_the_category();
   $categoryName = $category[0]->cat_name;

   if(stristr($categoryName,$firstSearchCategory))
    {
      echo "This is a Country Post!";

    }
    elseif(stristr($categoryName,$secondSearchCategory))
    {
        echo "This is a Rock Post!";

    }
    else
    {
       echo "This is NOT a Country Post or a Rock Post!";

    }

}

?>

Comments

Submit a Comment

No comments yet.

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)