Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Patrick Boehner
Patrick Boehner
2,005 Points

the_filed vs. get_post_meta

I might already know the answer to this question but I am asking out of curiosity.

In the video the example demonstrates using the Custom Field plugin's custom function the_filed for displaying the data held in our custom fields. I am assuming this is for simplicity sake as well as it being the method recommended by the plugin developers. But I am wondering if there is any other reason to use that method.

I ask because it would seem to build in a lot of dependency in your theme on the plugin. If you disable the plugin then you start getting error. Is there a reason for using this function over the one wordpress already has for handling the display of custom metadata, get_post_meta?

So instead of using:

<p><?php the_field('description'); ?></p>

We could use:

<p><?php echo get_post_meta( get_the_ID(), 'description', true ); ?></p>

That way we could avoid errors if the plugin is ever deactivated or another system is used for handling custom metadata fields.

2 Answers

Patrick Boehner
Patrick Boehner
2,005 Points

To give a more full answer I found after looking at ACF's documentation. They recommend using there the_field() because different ACF fields have different formatting options which change their output. For this example, get_post_meta() will work given that the custom fields we are using in ACF don't really have any formatting options. In some custom fields those custom formatting options are needed and get_post_meta() wont output them as expected. There may be a way around that but I would need to do some more looking. If there is, i would still think thats the preferred method despite requiring more work, that way your custom metadata isn't reliant on the plugin. Otherwise Stanley's suggestion would let you solve for an errors but would still cutoff the output of your metadata.

I also forgot to escape the output in my example above.

Stanley Thijssen
Stanley Thijssen
22,831 Points

For this plugin it's better to use the_field() function. You can add a conditional to only output code when the_field() function exists so you dont get any errors when the plugin is disabled.