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.

1350 views
d

By. Jacob

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().

Tell us what you think:

  1. How to insert code right after body opening tag, and creating a wrapper around the code in a page using PHP output buffering and the Wordpress shutdown hook.
  2. How to properly remove the title from a Wordpress post, and how to do it for specific post types.
  3. There is no function to select a post by slug name (post name), but we can create our own function to do it; find out how in this tutorial.
  4. How to properly customize Wordpress based website, where to add your own code, and how to override existing functionality.
  5. How to manually move a Wordpress website to another domain name, and copy the database and the files from the old site.

More in: WordPress Tutorials