Search code examples
wordpressadvanced-custom-fieldsdivi

ACF - Change post featured image based on user status


I’ve created a field group called ‘main_image’ and under it I have 2 fields 1. ‘main_image_logged’ type: image

2. ‘main_image_logout’ type:image

what im trying to do is to show the classic featured image which comes with the post for all, and for users that is logged in show the image in field “main_image_logged’

for the logout i even tried to set name:_thumbnail_id which took the image from ‘main_image_logout’ and used it as a featured image.

is there any way how to do this? if user is logged out -> featured image from field ‘main_image_logout’ if user is logged in -> featured image from field ‘main_image_logged’

tried something like this but it's wrong

function acf_set_featured_image( $value, $post_id, $field  ){
if (is_user_logged_in()) {    
    if($value != ''){
        //Add the value which is the image ID to the _thumbnail_id meta data for the current post
        add_post_meta($post_id, '_thumbnail_id', $value);
    }
 
    return $value;
}
}
add_filter('acf/update_value/name=main_image_logged', 'acf_set_featured_image', 10, 3);

using: Wordpress Advanced custom fields Divi theme

thanks alot guys


Solution

  • Try this

    add_filter('post_thumbnail_id', 'replace_thumbnail_id_with_acf', 20, 2);
    function replace_thumbnail_id_with_acf($thumbnail_id, $post) {
        if ( is_user_logged_in() ) {
            $image_id = get_field('reveal_face', $post->ID, false);
            if ($image_id) {
              $thumbnail_id = $image_id;
            }
        } else {
            $image_id = get_field('_thumbnail_id', $post->ID, false);
            if ($image_id) {
              $thumbnail_id = $image_id;
            }
        }
        return $thumbnail_id;
    }