0

I have a problem with a wp_localize_script in my functions.php file. I am trying to get a script localized for a custom post type ("gallery"), however, the error emerges that I am trying to access a property of non-object referring to $post. I assume that $post variable is undefined at this moment, but can't figure out what should I do to fix this. Should I use another hook action etc? If yes, what? So, basically, I have two questions - what should I do to fix this code and the second (more general one) - is there any good practice for using wp_localize_script (where should it be placed etc.)?

    function profolio_localize_script () {
        global $post; 
        if ($post->post_type==="my-gallery") {
            $layoutType=get_post_meta($post->ID,"gallery_layout",true);
            $data_array=array("layoutMode"=>$layoutType);
            wp_enqueue_script("custom", get_template_directory_uri () . "/js/custom.js", array("jquery","imagesLoaded","isotope"));
            wp_localize_script("custom","myGallery",$data_array); 
        }
    }
add_action("wp",  "profolio_localize_script");
1
  • Is this information not suffice to advise me? Commented Jan 15, 2015 at 14:25

1 Answer 1

0

The wp action hook fires pretty early, before the $post object is set. I would suggest using the appropriate hook wp_enqueue_scripts instead, and amending your code to:

function profolio_localize_script () {
    if ( is_singular( 'my-gallery' ) ) {
        $layoutType = get_post_meta( get_queried_object_id(), 'gallery_layout', true );
        // Rest of code 
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.