Last active
May 21, 2020 01:40
-
-
Save kingjmaningo/13566f507a8668fd931443a6fbda409f to your computer and use it in GitHub Desktop.
Get current post/page properties and use it on your scripts through JSON (Wordpress)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// In your wp_enqueue_scripts, just declare it when you localise your script or include it in your ajax array | |
add_action( 'wp_enqueue_scripts', 'wp_enqueue_child_scripts' ); | |
function wp_enqueue_child_scripts() { | |
// Globalize post variable to get current post data | |
global $post; | |
// Enqueue child script used | |
wp_enqueue_script( 'custom-name', get_stylesheet_directory_uri() . '/js/script.js', array( 'jquery' ) ); | |
// localized script used | |
wp_localize_script( | |
'custom-name', | |
'custom_ajax_function_name', | |
array( | |
'ajaxurl' => admin_url( 'admin-ajax.php' ), | |
// We use json_encode to convert arrays or object to JSON representation | |
'page_data' => json_encode($post) | |
) | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In your script, call data using JSON.parse() function | |
jQuery(document).ready(function($){ | |
var data = JSON.parse(custom_ajax_function_name.page_data); | |
//To get data list | |
console.log(data); | |
// Ex: Getting the post author ID | |
var author_id = data.post_author; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment