Joshua Leung
Joshua Leung

Reputation: 2399

How to get custom fields in single.php?

I am using Wordpress Timber to build my wordpress theme and would like to how to do I get custom fields in timber? I am referring to php files not twig template files.

Is there a function to get a custom field? Right now this approach doesn't work:

$post = new TimberPost();
$post->some_custom_field_name;

Upvotes: 0

Views: 1925

Answers (1)

Gchtr
Gchtr

Reputation: 2794

There are currently 3 different ways how you can access a custom field value when you have a Timber post. In Twig, it may be easier to write, but in the end, Twig is translated to PHP behind the scenes, so there surely is a way in PHP!

1. Direct access through the property

When you create a new Timber post, Timber will automatically populate your post object with the custom field values directly accessible as properties.

So if you have a custom field named some_custom_field_name, you should be able to access it the way you’ve tried it:

$custom_field_value = $post->some_custom_field_name;

If your value is not set, you can always check if there’s a property set on your post by dumping the contents with var_dump():

var_dump( $post );

Also refer to the Debugging Guide.

2. Access through the custom property

Timber also copies all the custom field values as an array to a property named custom on your post. So your field should also be accessible like this:

$custom_field_value = $post->custom['some_custom_field_name'];

3. Access through the meta method

The two methods described above will directly return the value of the database. If you use a plugin like Advanced Custom Fields, you might not want the raw value from the database, but a value that is properly filtered by the plugin. Then you should use the meta() method:

$custom_field_value = $post->meta('some_custom_field_name');

Upvotes: 1

Related Questions