ACF snippets

ACF (Advanced Custom Fields) is a great tool for adding custom fields to your WordPress websites. I have put together some of the most useful ACF snippets that you can use on your projects.

If you are unfamiliar with making coding adjustments to your functions, I would recommend backing your website up before making any adjustments to your themes code.

1. Hide admin page

This snippet should be added to your function files and will remove the ACF admin menu from WordPress.

add_filter('acf/settings/show_admin', '__return_false');

2. Register an options page

If you want to display some theme options on your project - you must register your options page first. Add this to your theme functions.

if( function_exists('acf_add_options_page') ) {

3. Change options page name

This snippet should be added to your function files and will change the name of the options page.

if (function_exists('acf_set_options_page_menu')){
	acf_set_options_page_menu('Your Title');

4. Position ACF above Yoast SEO Plugin

Add this to your functions.

add_filter( 'wpseo_metabox_prio', function() { return 'low';});

5. Select custom image size

If you want to use a custom image size, instead of the full sized image - use this in your templates.

$image = get_field('field-name'); $size = 'image-size-name';
if( $image ) {
    echo wp_get_attachment_image( $image, $size );

6. Print out URL for custom image size

$image = get_field('field-name');
$size = 'image-size-name';
if( $image ) {
    echo $image['sizes']['image-size-name'];

8. Speed up the post edit page

Add this snippet to your theme functions to speed up the post edit page.

add_filter('acf/settings/remove_wp_meta_box', '__return_true');

9. Create excerpts from ACF field

Firstly add this to your theme functions and change the field name to that of the field you wish to use:

function acf_excerpt() {
	global $post;
	$text = get_field('field_name');
	if ( '' != $text ) {
		$text = strip_shortcodes( $text );
		$text = apply_filters('the_content', $text);
		$text = str_replace(']]>', ']]>', $text);
		$excerpt_length = 20; // 20 words
		$excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
		$text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
	return apply_filters('the_excerpt', $text);

Then call the excerpt in your theme by using this snippet:

echo acf_excerpt();

You can reuse this for other fields if you want to, just duplicate and change the function name to something unique.