2

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(); ?>
lycrake
  • 45
  • 5

1 Answers1

1

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.

Fayaz
  • 9,047
  • 2
  • 33
  • 52