Using Custom Function With Advanced Custom Fields

I’ve written a custom function which works with the native WordPress custom fields function but I need it to work with the Advanced Custom Fields plugin.

I have created the custom field and meta box using the plugin and added the function to my child theme’s functions.php file.

Read More

I am using the field name (demo_field) for the meta box in the custom function but the meta box does not hook in to the function.

add_action( 'genesis_after_post_content', 'custom_field_before_content' );
function custom_field_before_content() {
  if(is_single() ) {
    genesis_custom_field('demo_field');
  }
}

What am I doing wrong?

Ok i fixed that but it doesn’t return the image even though i configured the settings to return value for the image object.

It displays the HTML for the image.

add_action( 'genesis_after_post_title', 'custom_field_before_content' );
function custom_field_before_content() {
if(is_single() ) {
the_field('second_image');
  }
}

Here’s what it displays:

32538, , second feature image, , , /wp-content/uploads/2013/06/second-feature-image.png, 600, 300, Array

Here’s the final solution i worked out myself which i tested and works with Genesis only. You can change the hook if using another theme with hooks.

add_action( 'genesis_after_post_title', 'custom_field_before_content' );
function custom_field_before_content() {
if(is_single() ) 
if( get_field('second_image') ):
?><img src="<?php the_field('second_image'); ?>" alt="" /><?php
endif;

}

The code comes from the ACF website.http://www.advancedcustomfields.com/resources/field-types/image/

Related posts

2 comments

  1. Any reason why you’re using genesis_custom_field()? Advanced custom fields has its own output functions. If you want to echo the demo_field you can use the function the_field('demo_field'); or if you want to use the value or save it as a variable you can use $demo = get_field('demo_field');.

  2. I have been trying to figure this out forever! Perfect solution, Ashraf.

    Just to clarify for other newbies like me…Go to the Advanced Custom Fields dashboard & edit the field where it says ‘Return Value’. Select the radio button for ‘Image URL’ instead of object or ID. It works perfectly in Genesis. Here is the code I’m using for my image field ‘rating_award_2’:

    add_action('genesis_sidebar', 'rating_award_2');
    
    function rating_award_2() {
    if(is_single() ) 
    if( get_field('rating_award_2') ):
    ?><img src="<?php the_field('rating_award_2'); ?>" alt="" /><?php
    endif;
    }
    

Comments are closed.