• Resolved Anonymous User 14123315

    (@anonymized-14123315)


    Hi there,

    I have a two part question.

    I was following this…
    https://ww.wp.xz.cn/support/topic/acf-field-integration/

    1) If there is no ACF field available, I would like to pull the first image from the ACF Gallery field

    2) Also, how do I create a fallback where if neither ACF field or gallery isn’t available, I show the default {thumb}

    
    $gallery = get_field('page_gallery', $post_id, false);
        if (!empty($gallery)) {
            $image_id = $gallery[0];
            set_post_thumbnail($post_id, $image_id);
        }
    
    • This topic was modified 5 years, 10 months ago by Anonymous User 14123315.
Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Author Hector Cabrera

    (@hcabrera)

    Hi @blingblingbling,

    1) If there is no ACF field available, I would like to pull the first image from the ACF Gallery field

    What do you mean with “no ACF field available?” All I see in your code is a single call to the get_field() function, is page_gallery the gallery field you’re referring to? If so then your code already retrieves the first image from the gallery: $gallery[0]. All you’d need to do is retrieve its data to build your ACF thumbnail, like this for example (untested code but you should get the idea):

    $first_img = $gallery[0];
    $thumbnail = '<img src="'. $first_img['url'] .'" alt="">';

    2) Also, how do I create a fallback where if neither ACF field or gallery isn’t available, I show the default {thumb}

    Returning the stock {thumb} content tag not possible. By the time this filter hook is executed you don’t get access to any of the “stock” Content Tags so you’d have to retrieve the thumbnail using regular WordPress functions, like get_the_post_thumbnail() for example.

    if (!empty($gallery)) {
        // The code that gets the first img from
        // the gallery
    } // Fallback
    else {
        // Retrieve the post thumbnail using 
        // regular WP functions
    }
    Thread Starter Anonymous User 14123315

    (@anonymized-14123315)

    Thanks for the reply! Oops, I guess I forgot to post the entire snippet.

    Yes, I was trying to see if the post had the field “gallery_featured_image” which would be a field that would add the featured_image to the post thru ACF. If that field was empty, it would select the first image from the gallery. My whole snippet was this … But it sounds like this might not be possible.

    
    /**
     * Parses custom content tags in WordPress Popular Posts.
     *
     * @param  string $html The HTML markup from the plugin.
     * @param  integer $post_id The post/page ID.
     * @return string
     */
    function wpp_parse_tags_in_popular_posts($html, $post_id)
    {
        $gallery = get_field('page_gallery');
    
        // If gallery is set
        if (!empty($gallery)) {
    
            // Replace custom content tag {gallery_featured_image} with an actual gallery_featured_image
            if (false !== strpos($html, '{gallery_featured_image}')) {
    
                // Get the gallery_featured_image from ACF
                $gallery_featured_image = get_field('gallery_featured_image', $post_id);
    
                // This post has a gallery_featured_image assigned via ACF,
                // so let's display it
                if ($gallery_featured_image) {
                    // Replace {gallery_featured_image} with the gallery_featured_image returned by ACF
                    $html = str_replace('{gallery_featured_image}', $image_id, $html);
                } // No gallery_featured_image found
            }
        }
    
        // Otherwise, set first image from gallery as thumb
        else {
            // Get first image from gallery
            $image_id = $gallery[0];
            $html = set_post_thumbnail($post_id, $image_id);
        }
    
        return $html;
    }
    

    But either way, if the field “gallery_featured_image” had an image, I would want that to take priority.

    • This reply was modified 5 years, 10 months ago by Anonymous User 14123315.
    Thread Starter Anonymous User 14123315

    (@anonymized-14123315)

    I thought I could maybe do something clever with this one — where this ACF hook would make the first gallery image the featured image, if the “gallery_featured_image” wasn’t set.

    OR

    Thinking of just doing an IF/ELSE on the initial $args
    I’m all over the place, sorry πŸ™

    Plugin Author Hector Cabrera

    (@hcabrera)

    There are a few issues with your code:

    1. Your first get_field() call won’t work as you expect it to.

    If you check the documentation of the get_field() function you’ll notice that it takes three parameters:

    • The field name (required.)
    • The post/page ID (optional.)
    • Format value (optional.)

    If the second parameter (the ID) is not provided, the get_field() function will default to the current post/page.

    Since you’re not passing the $post_id parameter to get_field(), this function will attempt to retrieve the page_gallery field from the current post/page. If you’re viewing the homepage, for example, chances are the function will return null/false and in consequence none of your popular posts will display the first gallery image.

    Likewise, if you’re currently viewing a post and said post does have a image gallery assigned to it then all of your popular posts will display the same image: remember, get_field() will default to the current post ID if you don’t explicitly provide an ID as a second parameter.

    So, to make sure your code works as intended, your first call to get_field() should look like this instead:

    $gallery = get_field('page_gallery', $post_id);

    2. You’re always calling the get_field() function in your code without checking first whether the {gallery_featured_image} tag is there or not.

    If you (or someone else) ever remove the {gallery_featured_image} tag from your HTML code the filter hook will still call the get_field() function, making several database read operations (one per popular post per page load) even though it might not be needed anymore which is a waste of server resources and might even have a performance impact under certain conditions.

    To avoid all that make sure to check first whether you need to call the get_field() function or not by checking whether the {gallery_featured_image} is present, like so:

    // Replace custom content tag {gallery_featured_image} 
    // with an actual gallery_featured_image
    if ( false !== strpos($html, '{gallery_featured_image}') ) {
        $gallery = get_field('page_gallery', $post_id);
    
        // Rest of the code goes here
    }
    
    return $html;

    3. You shouldn’t be using a third party plugin’s filter hook to set the post thumbnail of a post.

    The reason for this is that if someone ever decides to disable WordPress Popular Posts for some reason (or even replace it with a different plugin), then the code you’re using to automatically assign a featured image to a post from the gallery if it doesn’t have one already will stop working, then you will get angry calls/emails from the site owner (assuming it’s not you haha) and you’ll have to spend additional time trying to debug the issue only to realize that the problem happened because WPP isn’t active anymore.

    This kind of stuff should be done via your theme’s functions.php file or using a site specific plugin.

    Also, and for performance reasons, you’ll want to do this using a different hook. For example, I’d do this via the save_post hook to make sure that automatic featured image assignments only happen whenever someone creates and/or edits a post. The way you have it now in your code, featured images would be automatically assigned on every page load (when someone visits any page of the website where your popular post list is displayed) which -as you may already tell- might not be great for performance under certain circumstances, especially if your website is a high traffic one.

    So, with all that in mind, and assuming that gallery_featured_image is a regular ACF Image field, your code becomes this (untested, you may need to tweak stuff around):

    /**
     * Parses custom content tags in WordPress Popular Posts.
     *
     * @param  string $html The HTML markup from the plugin.
     * @param  integer $post_id The post/page ID.
     * @return string
     */
    function wpp_parse_tags_in_popular_posts($html, $post_id)
    {
        // Replace custom content tag {gallery_featured_image} 
        // with an actual gallery featured image
        if ( false !== strpos($html, '{gallery_featured_image}') ) {
            $image = null;
    
            // Get the gallery_featured_image from ACF
            $gallery_featured_image = get_field('gallery_featured_image', $post_id);
            
            // We have a Gallery Featured Image set
            if (
                is_array($gallery_featured_image) 
                && ! empty($gallery_featured_image)
            ) {
                $url = $gallery_featured_image['url'];
                $alt = esc_attr($gallery_featured_image['alt']);
                $image = '<img src="' . $url . '" alt="' . $alt . '">';
            } elseif ( is_numeric($gallery_featured_image) ) {
                $size = 'full';
                $image = wp_get_attachment_image($gallery_featured_image, $size);
            }
            // No featured gallery image found, fallback to first gallery image
            else {
                $gallery = get_field('page_gallery', $post_id, false);
                
                // We have a gallery set, get the first image
                if ( is_array($gallery) && ! empty($gallery) ) {
                    $first_image = $gallery[0];
                    $url = $first_image['url'];
                    $alt = esc_attr($first_image['alt']);
                    $image =  '<img src="' . $url . '" alt="' . $alt . '">';
                }
            }
    
            // We found an image, let's display it
            if ( $image ) {
                // Replace {gallery_featured_image} with the gallery_featured_image 
                // returned by ACF
                $html = str_replace('{gallery_featured_image}', $image, $html);
            }
            // No gallery_featured_image found, remove the content tag from output
            else {
                $html = str_replace('{gallery_featured_image}', '', $html);
            }
        }
    
        return $html;
    }
    add_filter("wpp_parse_custom_content_tags", "wpp_parse_tags_in_popular_posts", 10, 2);

    Feel free to add back your set_post_thumbnail() call if you want to (but I don’t recommend it.)

    • This reply was modified 5 years, 10 months ago by Hector Cabrera. Reason: Fixed typo
    • This reply was modified 5 years, 10 months ago by Hector Cabrera. Reason: Fixed in code
Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘ACF Integration with Fallback’ is closed to new replies.