Share via:

Using Get_field() to Access ACF in Code Snippets

How to obtain a field value from advanced custom fields in functions.php or the Code Snippets plugin in Wordpress.


Edited: 2019-11-09 05:33

To access Advanced Custom Fields from within Code Snippets, you should be able to use the get_field() function.

The following piece of code uses get_field(), and should both work from functions.php and the Code Snippets plugin:

add_filter('the_content',function($content) {
  return $content . '<p><b>' . get_field('my-field-name') . '<b></p>';

So what this does is, it takes the $content variable, and appends the content from a custom field to the end using concatenation. In this example, I just used a HTML paragraph (p) and turned the text bold with the b element.

Including an ID should not be necessary, since Wordpress will automatically try to use the ID of the current post. But, you can get the current post ID with get_the_ID():

get_field('my-field-name', get_the_ID());

Accessing Custom Fields

I have used the the_field() function when interacting with Advanced Custom Fields before without problems, but it does not seem to work when used in the Code Snippets plugin (an alternative to using functions.php). In my case, the get_field() function dis, however, work.

Wordpress development is driving me nuts sometimes. The documentation is simply incorrect or incomplete. You are told to do one thing, only to find out it does not work, and there is no indication as to why.

I found out, instead of using the_field to obtain the value of a custom field, you should be using get_field().