1

I'm trying to get a PHP variable that is created from some custom fields on a custom page (page-custom.php) inserted into a Javascript file.

The custom fields work perfectly, and the images are displayed on the page, but I can't get them into my Javascript file.

In my header.php at the top I have:

    function drum_scripts() {
        wp_enqueue_script( 'animated', get_template_directory_uri() . '/js/animated.js' );
        wp_localize_script('animated', 'MyScriptParams', array(
            'foo' => $meta['image'],
            )
        ); 
    }

    add_action( 'wp_enqueue_scripts', 'drum_scripts' );

In my javascript I have:

    $(function() {
        $(".animated").hover(
            function() {
                $(this).attr("src", MyScriptParams.foo);  
            },
            function() {
                $(this).attr("src", "img/gallery1_500px.jpg");
            }                         
        );                  
    });

and in page-custom.php I have:

    $custom_query = new WP_Query( $args );
    while ($custom_query->have_posts()) : $custom_query->the_post();

    $meta = get_post_meta( $post->ID, 'your_fields', true );

The javascript is working, but its not pulling the variable through. I know its something to do with the order of the code, but I'm not sure where to put it.

Here is the full code for page-custom.php

<?php get_header(); ?>

<!-- CONTAINER FOR CONTENT -->      
<div class="container">      

        <div class="row">

    <?php 

            $args =  array( 
               'post_type' => 'drummers',
               'orderby' => 'menu_order',
               'order' => 'ASC'
);

            $custom_query = new WP_Query( $args );
                while ($custom_query->have_posts()) : $custom_query->the_post();

            //GETS THE POST ID FROM WP_QUERY
            $post_id = get_the_ID();



            //PULLS THE DATA FROM THE CUSTOM FIELDS BOX ON DRUMMERS PAGE
            $meta = get_post_meta( $post->ID, 'your_fields', true );

            wp_localize_script('animated', 'MyScriptParams', array(
            'foo' => $meta['image']

        )
    );

echo $meta['image'];echo $meta['image'];echo $meta['image'];


    ?>

    <div class="col-md-4">

        <?php if ( has_post_thumbnail() ) {
                the_post_thumbnail('', array( 'class' => "img-fluid animated drummers_face$post_id"));
        } ?>


          <h2 class="drummers_face_detail<?php echo $post_id ?>"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
          <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p>

        <h1>Text Input</h1><?php echo $meta['text']; ?>

        <br />
        <img src="<?php echo $meta['image']; ?>">

        <?php echo $meta['image']; ?>


     </div><!-- END OF COLUMN-->

    <?php

            endwhile;
    ?>

     </div> <!-- END OF ROW -->

<?php get_footer(); ?>
0

Adding JavaScript with wp_enqueue_script:

Firstly, although it may work (if you add it before the call of wp_head()), but you should never add wp_enqueue_script CODE in header.php. Use theme's functions.php file for that.

Secondly, the following line in your CODE is problematic:

wp_enqueue_script( 'animated', get_template_directory_uri() . '/js/animated.js' );

As you've used jQuery in your animated.js file, you must say WordPress that it depends on jQuery. This is how you do that with CODE:

wp_enqueue_script( 'animated', get_template_directory_uri() . '/js/animated.js', array( 'jquery' ) );

Thirdly, you've assigned $meta variable in page-custom.php template file, so you can only call wp_localize_script after that, otherwise the variable will remain null. Also, since this template file will execute after header.php, you must add /js/animated.js in footer, like this:

wp_enqueue_script( 'animated', get_template_directory_uri() . '/js/animated.js', array( 'jquery' ), null, true );

So, your final CODE for adding /js/animated.js will be (in functions.php):

    // This CODE should be in functions.php file
    function drum_scripts() {
        wp_enqueue_script( 'animated', get_template_directory_uri() . '/js/animated.js', array( 'jquery' ), null, true );
    }

    add_action( 'wp_enqueue_scripts', 'drum_scripts' );

Placing wp_localize_script once the variable is accessible:

Since you are assigning the $meta variable in page-custom.php file, you should add the call to wp_localize_script there:

    $custom_query = new WP_Query( $args );
        while ($custom_query->have_posts()) : $custom_query->the_post();

    $meta = get_post_meta( $post->ID, 'your_fields', true );

    // $meta[image] is only accessible after the above CODE is executed
    wp_localize_script('animated', 'MyScriptParams', array(
            'foo' => $meta['image']
        )
    );

JavaScript CODE with jQuery:

jQuery $ variable may not be defined in that scope. So instead of using this CODE:

    $(function() {
        $(".animated").hover(
            function() {
                $(this).attr("src", MyScriptParams.foo);  
            },
            function() {
                $(this).attr("src", "img/gallery1_500px.jpg");
            }                         
        );                  
    });

Use the following CODE in your theme's /js/animated.js file:

    (function($) {
        // assuming you have .animated CSS class in the right place
        $(".animated").hover(
            function() {
                $(this).attr("src", MyScriptParams.foo);  
            },
            function() {
                $(this).attr("src", "img/gallery1_500px.jpg");
            }                         
        );
    })(jQuery);

Now if everything else is OK in your CODE, the modified CODE should work.

You may learn WordPress execution order from Here, if you want to know what's happening where.

Update:

Your page-custom.php doesn't look right at all. Definitely there are errors in your PHP file & many errors - which is out of scope for this question. However, Just to make sure wp_localize_script is working, use this simple CODE below for the page-custom.php file (only this CODE, not your CODE):

    <?php get_header(); ?>
    <!-- CONTAINER FOR CONTENT -->
    <div class="container">
        <div class="row">
        <?php
            wp_localize_script('animated', 'MyScriptParams', array(
                'foo' => "It Works!"
                )
            );
        ?>
        </div> <!-- END OF ROW -->
    <?php get_footer(); ?>

The rule of thumb for debugging a problem is to make simple things right first & then build up from that. We can't fix many problems at once. If after using the above CODE your alert is It Works!, then you'll know for sure that the problem is in your PHP CODE.

  • Thanks very much for your help, much appreciated. I had my wp_enqueue_scripts in functions.php already (my mistake in my question) but didn't call it in the footer. I've done all the above, but still not having any luck. I've commented out the anmated.js code above to eradicate that as an issue, and just put alert(MyScriptParams.foo); at the top of the js file. It alerts, but is still blank. Must be something to do with the wp_localized_script... – lycrake Feb 12 '17 at 11:34
  • And I can echo $meta['image']; in the page-custom.php, so the php is working... – lycrake Feb 12 '17 at 11:58
  • I just checked the same in my setup (just to be sure), it works fine. Can you please provide the full CODE of page-custom.php file, may be there are some error there. Also, what WP version are you using? – Fayaz Feb 12 '17 at 12:02
  • Thanks for all your help, I've added in the full code above. Using v 4.7.2 that I installed yesterday. – lycrake Feb 12 '17 at 12:15
  • 1
    Great thanks for the help. I've realised what I've done thanks to you. I was puzzled at your response, as my code has all been sound. So I double checked from the beginning and realised I stupidly used another page as the basis to start this page that didn't involve custom meta boxes, so obviously all the PHP was different. It now pulls through perfectly. I will update my question with the final code so this should help other people! – lycrake Feb 12 '17 at 16:22

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.