skip to Main Content

Website link: https://colindedeugd.nl/stories

I have build a website with WordPress and Divi. I am running into an issue, I hope you know the problem!

I have a custom Divi Blog Module. This not only grabs the default information from my blog posts, but also the info from a custom ACF image field (this was done with the help of Divi support, and some changes to my child theme and seems to work). The code below should then load the image from this custom field (currently set as Image URL return format) and input it as the module background. It get’s as far as loading the correct image ID (I checked this with the inspect element tool) but fails to properly load the image. I hope someone knows what is going wrong! Here’s the Javascript code I added to the page:

<script>
jQuery(document).ready(function($) {
    // Searches for the Divi Blog Modules with this CSS Class where I want the background replaced
    var $module = $('.acf-blog-bg');
    
    // Checks if the module exists on the page
    if ($module.length) {
        // Retrieve the URL of the featured image using PHP
        var imageUrl = "<?php echo esc_js(wp_get_attachment_url(get_post_meta(get_the_ID(), 'featured_portrait', true))); ?>";
        
        // Check if the image URL is not empty
        if (imageUrl !== '') {
            // Sets the background of the module to the URL of the image file
            $module.css('background-image', 'url(' + imageUrl + ')');
        }
    }
});
</script>

I’m not a coder and this code was written with ChatGPT, so if there are any glaring issues please let me know! I hope someone finds the fix! Thanks!


For some additional context:

This was added to Blog.php (a copy of the Blog.php Module in my child theme) at around line 1640, to grab the data from the custom image field

                    $featured_portrait = get_post_meta($post->ID, 'featured_portrait', true) ? get_post_meta($post->ID, 'featured_portrait', true) : "";
if($featured_portrait != "") { 
    echo '<div class="featured_portrait"><img src="' . $featured_portrait . '" alt="Featured Portrait"></div>'; 
}

And this was added to my functions.php to load the custom Blog Module:

function divi_custom_blog_module() { 
get_template_part( '/includes/Blog' ); 
$dcfm = new custom_ET_Builder_Module_Blog(); 
remove_shortcode( 'et_pb_blog' ); 
add_shortcode( 'et_pb_blog', array( $dcfm, '_shortcode_callback' ) ); } 

add_action( 'et_builder_ready', 'divi_custom_blog_module' ); 

function divi_custom_blog_class( $classlist ) { 
// Blog Module 'classname' overwrite. 
$classlist['et_pb_blog'] = array( 'classname' => 'custom_ET_Builder_Module_Blog',); 
return $classlist; 
} 

add_filter( 'et_module_classes', 'divi_custom_blog_class' );

2

Answers


  1. Chosen as BEST ANSWER

    So if anyone comes across this, I found a different way that finally fixes the problem. Turns out I was going down a difficult route. Here's how you do it:

    First, we need to make sure the blog meta gets shown on top of the featured image, instead of below. (credits to: https://www.peeayecreative.com/how-to-move-the-divi-blog-title-text-and-button-over-the-image/)

    Give the Blog Modules you want to apply this to the following CSS Class pa-blog and paste this in your functions.php or in a Code Module:

    <script>
        (function($) {
            $(document).ready(function() {
                $(".pa-blog .et_pb_post").each(function() {
                    $(this).find(".entry-title, .post-meta, .post-content ").wrapAll('<div class="pa-blog-text"></div>');
                });
                //Do the same for ajax
                $(document).bind('ready ajaxComplete', function() {
                    $(".pa-blog .et_pb_post").each(function() {
                        $(this).find(".entry-title, .post-meta, .post-content ").wrapAll('<div class="pa-blog-text"></div>');
                    });
                });
            });
        })(jQuery); 
    </script>
    

    Next, we need to add this to our Theme Options > Custom CSS:

    /*move wrapped title, meta, and text up over the image*/
    .pa-blog-text {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
        padding: 30px;
        z-index: 1;
    }
    /*keep the moved items positioned with their parent items*/
    .et_pb_blog_grid article {
        position: relative;
    }
    /*remove spacing around entire blog post*/
    .et_pb_blog_grid .et_pb_post {
        padding: 0px;
    }
    /*remove negative margins on blog featured image*/
    .et_pb_image_container {
        margin: 0;
    }
    /*remove the margin below the featured image frame*/
    .et_pb_post .entry-featured-image-url {
        margin: 0;
    }
    .et_pb_blog_grid .entry-featured-image-url::before {
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
    }
    

    We can use this to style our module. For example, to change the margins around the text field, you can change the padding. There is one thing left. By default, Divi shows the Featured Images as a 1x1 image. You can set this to be a custom size (https://www.peeayecreative.com/change-the-divi-blog-image-aspect-ratio/) or what I'm doing, stop Divi from cropping them altogether (https://www.peeayecreative.com/change-the-divi-blog-image-aspect-ratio/). You can then set your own size by uploading your images in the correct dimensions.

    To stop Divi from cropping, paste this in your functions.php:

    function wpc_remove_height_cropping($height) {
        return '9999';
    }
    function wpc_remove_width_cropping($width) {
        return '9999';
    }
    
    add_filter( 'et_pb_blog_image_height', 'wpc_remove_height_cropping' );
    add_filter( 'et_pb_blog_image_width', 'wpc_remove_width_cropping' );
    

    Unfortunately what I needed at first, to change the source where the Featured Image comes from, is not possible, because Dynamic Content is based on the content of the current page, not from the posts. But at least with this method the image will automatically change!


  2. So your main problem is that you are enqueue a JavaScript file and your browser is requesting it. Because the file ends with .js, the PHP interpreter doesn’t kick in.

    You could try renaming it to .php, and that’d honestly work, however it wouldn’t be run in a "WordPress context", so functions such as get_the_ID would fail. Some people attempt to fix this by booting a mini copy of WordPress then, however in this case it would still fail because the URL of the JavaScript file doesn’t tell WordPress anything about the page holding it, so WordPress wouldn’t know the page and thus the field on it.

    The better solution is probably to create a JavaScript variable that holds the result of the PHP execution, which is exactly what wp_localize_script does.

    In the code below I’m enqueuing your JavaScript in mostly the same way as you were doing it before. After enqueueing, I’m then calling wp_localize_script with the result of your wp_get_attachment_url call.

    add_action(
        'wp_enqueue_scripts',
        static function () {
    
            // The following three conditions are effectively the same as you had before in
            // a one-liner, I've just broken them out for clarity. If this ever stops working,
            // instead of "return" you can "echo 'first block';" or "echo 'second block';".
            if (!$id = get_the_ID()) {
                return;
            }
    
            if (!$featuredPortrait = get_post_meta($id, 'featured_portrait', true)) {
                return;
            }
    
            if (!$imageUrl = wp_get_attachment_url($featuredPortrait)) {
                return;
            }
    
            // Let's give it a more descriptive name. We'll use this both for
            // enqueuing the script and for localizing the script.
            $customScriptName = 'colindedeugd-custom-scripts';
    
            wp_enqueue_script(
                $customScriptName,
                get_stylesheet_directory_uri().'/js/background-customacf-loadscript.js'
            );
            
            // Although "localize" is associated with internationalization, it's also
            // used to pass data from PHP to JavaScript. This will create a global
            // JavaScript variable called "colindedeugd_custom_scripts" with a property
            // called "imageUrl" that contains the URL of the featured image.
            wp_localize_script(
                $customScriptName,
                'colindedeugd_custom_scripts',
                [
                    'imageUrl' => $imageUrl,
                ]
            );
        }
    );
    

    The result of the above is that a global variable called window.colindedeugd_custom_scripts.imageUrl will be created, and that should hold your URL for you.

    Assuming the first block of JavaScript is what was in background-customacf-loadscript.js (minus the script tags), you can replace it with:

        jQuery(document).ready(function ($) {
            // Searches for the Divi Blog Modules with this CSS Class where I want the background replaced
            var $module = $('.acf-blog-bg');
    
            // Checks if the module exists on the page
            if ($module.length) {
                // Retrieve the URL of the featured image using PHP
                var imageUrl = window.colindedeugd_custom_scripts.imageUrl;
    
                // Check if the image URL is not empty
                if (imageUrl !== '') {
                    // Sets the background of the module to the URL of the image file
                    $module.css('background-image', 'url(' + imageUrl + ')');
                }
            }
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search