0

I am trying to localize a variable in a javascript below.. The scenario is that I want to dynamically get the post_id and localize it in the jquery I have enqueued through wp_enqueue_scripts. Here's my code:

function add_scripts() {
     wp_enqueue_style('jplayercss',plugins_url( 'skin/jplayer.blue.monday.css',__FILE__));
     wp_enqueue_script( 'jplayer',plugins_url( 'js/jquery.jplayer.min.js' , __FILE__ ) );
     wp_enqueue_script( 'jplayerjs',plugins_url( 'js/mfsjplayer.js',__FILE__), array('jquery') ); 
}
add_action( 'wp_enqueue_scripts', 'add_scripts' );

and i am calling it in a different function in the content_filter hook,

function the_content_filter( $content ) {

    $post_id        =  $GLOBALS['post']->ID;
    $accessToken    = get_option( 'dropbox_api_token' );
    $dbxClient      = new dbx\Client($accessToken, "PHP-Example/1.0");
    $file_url_array = $dbxClient->createTemporaryDirectLink( "/recorded_file".$post_id.".wav" );
    $file_url       = isset( $file_url_array ) ? $file_url_array[0] : '';
    if ( ! empty( $file_url ) ) {
        require("lib/mfs_jplayer_interface.php");   
        $site_parameters = array(
              'file_url' => $file_url,
              'plugin_url' => plugins_url(),
              'theme_directory' => get_template_directory_uri(),
              'post_id' => $post_id,
        ); 
        $upload_dir = wp_upload_dir();
        $upload_loc = $upload_dir['baseurl']."/recorded_files";
        wp_localize_script( 'jplayerjs', 'mfs_var', $site_parameters ); 
    }
// Add play and record buttons to each post
// Returns the content.
return $content;
}
 add_filter( 'the_content', 'the_content_filter', 20 );

So I am getting mfs_var as undefined variable in console. Please can anyone help me in solving the issue. Thanks, in advance.

1 Answer 1

1

the_content filter is (most likely) running long after you scripts were output.

You need to either:

  1. Run localize logic earlier.
  2. Enqueue scripts for footer, using respective wp_enqueue_script() argument.
1
  • Thanks @Rarst, it worked. But when i alert mfs_var.post_id, it gets the post_id of only the first post rather than alerting all the post_ids of each posts.. Commented Nov 10, 2014 at 15:46

Your Answer

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

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