0

The featured image (for posts & pages) in my theme is a header background image.
Actually each featured image is retrieved by the following function in functions.php :

function mytheme_header_style() {
    // Declare $post global if used outside of the loop.
    $post = get_post();
    // Check if post is object otherwise we're not in singular post.
    if (!is_object($post)) {
        return;
    }
    // If Object
    $backgroundImg = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), '');
    // Add inline style to the backgroung header image.
    if (has_post_thumbnail()) {
        $custom_header_style = '
            .intro-header {
                background-image: url( ' . $backgroundImg[0] . ' );
            }
        ';
    } else {
        $custom_header_style = '
            .intro-header {
                background-image: url( ' . get_template_directory_uri() . '/components/header/images/default-hero.jpg' . ' );
            }
        ';
    }
    wp_add_inline_style( 'mytheme-main-style', $custom_header_style );
}
add_action( 'wp_enqueue_scripts', 'mytheme_header_style' );

This background image is responsive and manipulated by a jQuery function in a separated hero.js file to always be fullscreen on any device/screen size like so :

jQuery(document).ready(function ($) {
    // Defining a function to set size for #masthead 
    function fullscreen() {
        jQuery('#masthead').css({
            width: jQuery(window).width(),
            height: jQuery(window).height()
        });
    }

    fullscreen();

    // Run the function in case of window resize
    jQuery(window).resize(function () {
        fullscreen();
    });

});

The HTML structure of header.php makes this featured background header image separated from the main content like so :

<body>
  <div id="page">
    <nav>...</nav>
     <!-- Page Header -->
     <?php
     if (is_404()) {
         get_template_part('components/header/bg', '404');
     } elseif (is_search()) {
         get_template_part('components/header/bg', 'search');
     } else {
         get_template_part('components/header/bg', 'header'); // mytheme_header_style() is called here
     }
     ?>
    <!-- Main Content -->
    <div id="content">...</div>
  </div>//#page
  <footer>...</footer>
</body>

I'm trying the following
1- localize hero.js

function mytheme_header_style_script() {

        // Adding custom javascript header style file to theme.
        wp_enqueue_script('mytheme-hero', get_theme_file_uri() . '/assets/js/hero.js', array('jquery'));
        wp_localize_script('mytheme-hero', 'hero_ajax', array('ajaxurl' => admin_url( 'admin-ajax.php' )));

}
add_action('wp_enqueue_scripts', 'mytheme_header_style_script');

2- add wp_ajax action to mytheme_header_style() function

add_action( 'wp_enqueue_scripts', 'mytheme_header_style' );
add_action('wp_ajax_heroajax', 'mytheme_header_style');
add_action('wp_ajax_nopriv_heroajax', 'mytheme_header_style');

3- Then I've changed the hero.js like so :

jQuery(document).ready(function() {
  // Handler for .ready() called.
    $.ajax({
        type: "post",
        url: hero_ajax.ajaxurl,
        data: {
            action : 'heroajax'
        },
        // callback handler that will be called on success
        // Defining a function to set size for #masthead
        success: function fullscreen(imageUrl, textStatus, jqXHR){
            // log a message to the console
            console.log("Hooray, it worked! Load The Image Here");
                $('#masthead').css({
                    width: $(window).width(),
                    height: $(window).height()
                });
                $('#masthead').css('background-image', 'url(' + DefaultimageUrl + ')');
        },
        // callback handler that will be called on error
        error: function(jqXHR, textStatus, errorThrown){
            DefaultimageUrl = 'path/to/default/image.jpg';                        
            // log the error to the console
            console.log(
                "Load Default Image here! The following error occured: "+
                textStatus, errorThrown
            );
            $('#masthead').css('background-image', 'url(' + DefaultimageUrl + ')');
        }
    });

    fullscreen();

    // Run the function in case of window resize
    $(window).resize(function () {
        fullscreen();
    });

});

This is not working, the featured background header image is no longer full screen and the JS debugger is highlighting $.ajax and says Paused on Exception and I'm not getting any message in the console.
What I'm doing wrong ? Much appreciate your help, thanks in advance everyone.

0

It was easier than i thought.
After a lot of reading and trying I've finally got it !
This is the answer with explications if it can help someone.
1- In functions.php localize hero.js

function mytheme_header_script() {

    // Adding custom javascript file to handle the header image.
    wp_enqueue_script('mytheme-hero', get_theme_file_uri() . '/assets/js/hero.js', array('jquery'), '', true); // I'm putting the script in the footer

    // Declare $post global if used outside of the loop.
    $post = get_post();

    // Retrieve the featured image by using wp_get_attachment_image_src
    // and include the id of the post as a parameter for get_post_thumbnail_id (which we retrieve using $post->id)
    $heroImg = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), '');

    // This is an array of values that we will use each by it's key in hero.js script file
    $heroSettings = array (
        'featured_image'     => $heroImg[0], // Retrieve the featured image and display it if set
        'default_image'      => get_template_directory_uri() . '/components/header/images/default-hero.jpg', // Display the default image if no featured image is set
        'has_post_thumbnail' => has_post_thumbnail(), // To use the function in js
        'ajaxurl'            => admin_url( 'admin-ajax.php' ), // The URL to admin-ajax.php
        'success'            => 'Hooray, it worked! The featured image is loaded', // Print this message in the console if the featured image is displayed
        'default'            => 'The default image is loaded' // Print this message in the console if the default image is displayed
    );
    // Now use the wp_localize_script function
    // Set the same $handle as the script to localize it
    // hero-set is the name of the js variable that will contain the data
    // $heroSettings is the array of data to retrieve in js by hero_set
    wp_localize_script('mytheme-hero', 'hero_set', $heroSettings);
}
add_action('wp_enqueue_scripts', 'mytheme_header_script');

2- Still the same :)

3- hero.js became this

(function($) {

    // Define the fullscreen function
    fullscreen();

    // Tell the fullscreen function what to do using ajax
    function fullscreen() {
        $.ajax({
            type: 'POST', // use $_POST method to submit the data
            url: hero_set.ajaxurl, // submit the data to admin-ajax.php
            data: {
                action : 'mytheme_header_style'
                // process mytheme_header_style function by the requested data action
            },
            // use beforeSend so the background header image is retrieved and displayed
            // wright away before anything else to speed the page load
            beforeSend : function(){
                // if a featured image is set
                if (hero_set.has_post_thumbnail){
                    // log the success message to the console
                    console.log(hero_set.success);
                    $('#masthead').css({
                        'background-image': 'url(' + hero_set.featured_image + ')',
                        width: $(window).width(),
                        height: $(window).height()
                    });
                } else {
                    // if no featured image is set
                    // log the default message to the console
                    console.log(hero_set.default);
                    $('#masthead').css({
                        'background-image': 'url(' + hero_set.default_image + ')',
                        width: $(window).width(),
                        height: $(window).height()
                    });
                }
            }
        });
    }

    // Run the function in case of window resize.
    $(window).resize(function(e) {
        e.preventDefault();
        fullscreen();
    });
})(jQuery);

That's all folks, hope it will help someone.
SYA

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.