Conditionally Display Specific Custom Fields in WordPress

When I was creating my theme for my portfolio website, I used Custom Post Types and Custom Fields to tailor the way I display my projects, whether they be websites, plugins, code snippets, etc. In some cases I would want to provide a link to a website for the project, in other cases a link to the project on GitHub, or I might want to link to both places. I created custom fields for links to the website URL and links to the project on GitHub.  The issue was how to conditionally display one, the other, or both when I posted a new project. Here is the solution is used:

I used the get_post_meta() function within the loop to return the value held in the custom post field. The get_post_meta() function takes three parameters:

The first parameter is required and references the post id of the post data. In my case I’ve use “$post->ID” which will refer to the current post Id in the loop. The second parameter is optional and refers to the name of the meta value you want. The third parameter is a boolean with true returning a single value (which is what I want), or false which would return and array of all the custom fields (false is the default).

In my code I check for the existence of the custom field with an “if” statement. If the specific custom filed exists for the post in the loop, I catch that value in a variable ($weburl), then display that $weburl variable within my html.

I used the same code block with a few tweaks to check for the link_to_github custom field. Just as with the code above, I use the “if” statement to check for the existence and output the field with it’s proper html code.

A pretty nice solution to conditionally displaying specific custom fields in WordPress. And, I can add additional code blocks to handle any other or future custom fields I might with to conditionally display.


get_post_meta() function in the WordPress Codex 

Leave a Reply