Support

Account

Home Forums Backend Issues (wp-admin) Set WordPress excerpt and post thumbnail based on custom field

Solved

Set WordPress excerpt and post thumbnail based on custom field

  • As stated in the title, I would like to automatically save/update the value of post_excerpt and post_thumbnail based on an ACF custom field (mostly for compatibily reasons with other plugins). Now, I’ve came up with the following code:

    
    add_action('acf/save_post', 'flex_FeaturedImageSetByACF', 20);
    
    function flex_FeaturedImageSetByACF() {
    
        $current_screen         = get_current_screen(); // Current admin screen needed to identify the current cpt
        $current_cpt_name       = $current_screen->post_type; // Current cpt name
        $current_cpt_support    = 'thumbnail'; // We want to check if the CPT supports this feature
    
        $post_id                = get_the_ID(); // Current post ID
        $post_image_field       = get_field('post_head_img'); // ACF field we want to sync
        $post_image_id          = $post_image_field['id']; // ACF image filed ID
        $post_image_url         = $post_image_field['url']; // ACF image filed URL
    
        // If current cpt supports thumbnails/featured images
    
        if ( post_type_supports( $current_cpt_name, $current_cpt_support ) ) {
    
            if ( ( $post_image_url ) AND ( ( $post_image_url ) != ( get_the_post_thumbnail() ) ) ) {
    
                delete_post_thumbnail( $post_id );
                set_post_thumbnail( $post_id, $post_image_id );
    
            }
    
        }
    
    }
    

    This code works to some extend: using get_field(‘post_head_img’) I can retrieve the (previous) saved value of the field, which means the functions itself does works… but requires me to save twice. On http://www.stackoverflow.com, the only suggestion I received was to use the acf/save_post hook instead, which led me to read some more of this process, to undestand I’m not supposed to use get_field but should instead try to retrieve the current field value before it does get saved. And this is where I’m lost: I’ve read https://www.advancedcustomfields.com/resources/acfsave_post/ but I don’t seem to be able to grasp how to continue from here on. To be more specific, the documentations suggest to work with $_POST/$_POST[‘acf’], which seems to be empty for me (which I’m probably calling/hooking it at the wrong time or place).

    Do you think you could help me get past this point? Thanks in advance

  • ACF uses a Priority of 10 to do it’s own work on the acf/save_post hook.

    If you use a priority < 10 then your action will run before ACF. The values in the database will be the previous values and using get_field() at this point will return then previous values and not the new values that need to be saved.

    If you use a priority > 10 then your action will run after ACF has saved the new values to the DB. Using get get_field() here will return the newly saved values.

    The $_POST value that you should be looking at depends on what version of ACF you are using.

    In ACF5 it is $_POST['acf']

    In ACF4 you need to look at $_POST['fields']

    The nested index of the array for each field is the field key. For example $_POST['acf']['field_1234567890123]or$_POST[‘fields’][‘field_1234567890123] These values are the same no matter what priority you use for your action.

  • Thanks, you’ve been incredibly helpful! Granted my code (which I pasted below) may or may not make you and others cringe in horror, I managed to make it work somehow (I’ve put together a function that handles featured images and custom excerpt one).

    Now, I did a lot of testing and I found that both functions work correctly with the hook “save_post” instead of “acf/save_post“. I’m not sure why, as I’m not sure why if I switch to “acf/save_post“, only the featured image function keeps working (while the excerpt one, “reads” the previous saved value, hence requiring me to save twice). If I then try to lower the priority I receive some internal server errors. But I guess I’m more puzzled at this point as wheter what I accomplished is indeed correct or it’s faulty (and this is the reason it does not work with “acf/save_post”).

    In any way, thanks again for pointing me in the right direction!

    
    add_action('save_post', 'flex_CustomExcerptSetByACF', 50);
    function flex_CustomExcerptSetByACF() {
    
        global $post;
    
        $post_id        = ( $post->ID ); // Current post ID
        $post_excerpt   = get_field( 'post_excerpt', $post_id ); // ACF field
    
        if ( ( $post_id ) AND ( $post_excerpt ) ) {
    
            $post_array     = array(
    
                'ID'            => $post_id,
                'post_excerpt'	=> $post_excerpt
    
            );
    
            remove_action('save_post', 'flex_CustomExcerptSetByACF', 50); // Unhook this function so it doesn't loop infinitely
    
            wp_update_post( $post_array );
    
            add_action( 'save_post', 'flex_CustomExcerptSetByACF', 50); // Re-hook this function
    
        }
    
    }
    
    add_action('save_post', 'flex_FeaturedImageSetByACF', 50);
    
    function flex_FeaturedImageSetByACF() {
    
        $current_screen         = get_current_screen(); // Current admin screen needed to identify the current cpt
        $current_cpt_name       = $current_screen->post_type; // Current cpt name
        $current_cpt_support    = 'thumbnail'; // We want to check if the CPT supports this feature
    
        global $post;
    
        $post_id                = ( $post->ID ); // Current post ID
        $post_image_field       = get_field('post_head_img', $post_id ); // ACF field
    
        if ( ( $post_id ) AND ( $post_image_field ) ) {
    
            $post_image_id          = $post_image_field['id']; // ACF image filed ID
            $post_image_url         = $post_image_field['url']; // ACF image filed URL
    
            // If current cpt supports thumbnails/featured images
    
            if ( post_type_supports( $current_cpt_name, $current_cpt_support ) ) {
    
                if ( ( $post_image_url ) AND ( ( $post_image_url ) != ( get_the_post_thumbnail() ) ) ) {
    
                    update_post_meta($post_id, '_thumbnail_id', $post_image_id);
    
                }
    
            }
    
        }
    
    }
    
  • What version of ACF are you using?

  • Advanced Custom Fields PRO 5.3.9

  • I was curious because you said that acf/save_post is not working. ACF4 uses acf_save_post, but if you’re using ACF5 then there isn’t any reason it shouldn’t be working.

    The code used when using acf/save_post should be different. For one thing acf passes your action function the post ID so you don’t need to go through the trouble of figuring out what it is.

    When using acf/save_post or save_post hooks, there is a change of creating an infinite loop and you need to remove the action and add it again. This is probably the cause of your internal server error. https://codex.wordpress.org/Plugin_API/Action_Reference/save_post#Avoiding_infinite_loops

  • @foyle The code above is still working in the latest version of ACF PRO? I try it but it does not seem to do what it should do. I’m not an expert, that’s true. I try to use your code to show the featured image and excerpt inside Search results page.
    Any help will be appreciated.
    Thanks

  • I ended up using a sligtily modified version. You have to place this code in your functions.php and have to save each individual post in order to show/update your featured image (unfortunately, if you already have many posts this may prove to be a tedious task). Make sure you run these functions only for the custom post types you need.

    
    
    add_action('acf/save_post', 'flex_CustomExcerptSetByACF', 50);
    
    function flex_CustomExcerptSetByACF() {
    
        global $post;
    
        $post_id        = ( $post->ID ); // Current post ID
        $post_excerpt   = get_field( 'post_excerpt', $post_id ); // ACF field
    
        if ( ( !empty( $post_id ) ) AND ( $post_excerpt ) ) {
    
            $post_array     = array(
    
                'ID'            => $post_id,
                'post_excerpt'	=> $post_excerpt
    
            );
    
            remove_action('save_post', 'flex_CustomExcerptSetByACF', 50); // Unhook this function so it doesn't loop infinitely
    
            wp_update_post( $post_array );
    
            add_action( 'save_post', 'flex_CustomExcerptSetByACF', 50); // Re-hook this function
    
        }
    
    }
    
    add_action('acf/save_post', 'flex_FeaturedImageSetByACF', 50);
    
    function flex_FeaturedImageSetByACF() {
    
        $current_screen         = get_current_screen(); // Current admin screen needed to identify the current cpt
        $current_cpt_name       = $current_screen->post_type; // Current cpt name
        $current_cpt_support    = 'thumbnail'; // We want to check if the CPT supports this feature
    
        global $post;
    
        $post_id                = ( $post->ID ); // Current post ID
        $post_image_field       = get_field('post_head_img', $post_id ); // ACF field
    
        if  ( !empty( $post_id ) ) {
    
            if ( !empty( $post_image_field ) ) {
    
                $post_image_id          = $post_image_field['id']; // ACF image filed ID
                $post_image_url         = $post_image_field['url']; // ACF image filed URL
    
                // If current cpt supports thumbnails/featured images
    
                if ( post_type_supports( $current_cpt_name, $current_cpt_support ) ) {
    
                    if ( ( $post_image_url ) AND ( ( $post_image_url ) != ( get_the_post_thumbnail() ) ) ) {
    
                        update_post_meta($post_id, '_thumbnail_id', $post_image_id);
    
                    }
    
                }
    
            } else {
    
                update_post_meta( $post_id, '_thumbnail_id', 0 );
    
            }
    
        }
    
    }
    
    

    On a side note, if your issue is limited to showing exceprt & featured images on certain template files, it may prove easier to edit these.

  • You’re the best @foyle !!!!
    Thank you so much for sharing your code! It works perfectly for the excerpt.
    I just got an issue with the featured image. I don’t use a special image field, I use a gallery field for images. Can you please tell me how can I grab the first image from the gallery and used in your $post_image_field ?

    Thank you so much!!!
    Gabriel

  • Try with the following code (make sure to either remove or rename the above/previous featured image function). Just replace your gallery field with get_field(‘thisisyourgalleryfield’, $post_id ) and see if it works.

    
    add_action('acf/save_post', 'flex_FeaturedImageSetByACF', 50);
    
    function flex_FeaturedImageSetByACF() {
    
        $current_screen         = get_current_screen(); // Current admin screen needed to identify the current cpt
        $current_cpt_name       = $current_screen->post_type; // Current cpt name
        $current_cpt_support    = 'thumbnail'; // We want to check if the CPT supports this feature
    
        global $post;
    
        $post_id                = ( $post->ID ); // Current post ID
        $post_gallery_field     = get_field('thisisyourgalleryfield', $post_id ); // ACF field
    
        if  ( !empty( $post_id ) ) {
    
            if ( isset( $post_gallery_field['0'] ) ) {
    
                $post_image_id          = $post_gallery_field['0']['id']; // ACF image filed ID
                $post_image_url         = $post_gallery_field['0']['url']; // ACF image filed URL
    
                // If current cpt supports thumbnails/featured images
    
                if ( post_type_supports( $current_cpt_name, $current_cpt_support ) ) {
    
                    if ( ( $post_image_url ) AND ( ( $post_image_url ) != ( get_the_post_thumbnail() ) ) ) {
    
                        update_post_meta($post_id, '_thumbnail_id', $post_image_id);
    
                    }
    
                }
    
            } else {
    
                update_post_meta( $post_id, '_thumbnail_id', 0 );
    
            }
    
        }
    
    }
  • @foyle Thank you so much!!!!! It worked perfectly!

    I’m so grateful!

    Thanks!

Viewing 11 posts - 1 through 11 (of 11 total)

The topic ‘Set WordPress excerpt and post thumbnail based on custom field’ is closed to new replies.