Charly Anderson | Blog - Handy Wordpress Snippets

ACF Snippets

ACF is a great tool for adding custom fields to your Wordpress websites. I have put together some of the most useful ACF snippets.

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. Only display if field has a value

If you have a section of content that you want to hide when empty, use this snippet in your theme. Anything between the two tags will be hidden if the field is empty.

<?php if(get_field('field_name')) { ?>
 		<p>This will be hidden if field is empty</p>

<?php } ?>

9. 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');

10. 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(']]&gt;', ']]&gt;', $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:

<?php echo acf_excerpt(); ?>

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

Nov 13 2017 ,
Charly November 13th, 2017