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");
  • Is this information not suffice to advise me? – user3695711 Jan 15 '15 at 14:25
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, privacy policy and cookie policy

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