Thêm thẻ script vào footer nó không hoạt động & giải thích lý do (ok)
Ví dụ như trường hợp ở trang chủ nó chưa sử dụng jquery bao giờ do đó nó không được gọi ra khi ta vô tình sử dụng thẻ
jQuery(document).ready(function($) {
(index):137 Uncaught ReferenceError: jQuery is not defined
});
// (index):137 Uncaught ReferenceError: jQuery is not defined
Giải thích lý do vì nó chưa sử dụng những khai báo phụ thuộc jquey kiểu như
function wp_plugin_enqueue_scripts() {
wp_enqueue_script( 'script-name', plugin_dir_url(__FILE__) . '/main.js', array('jquery') );
}
add_action( 'wp_enqueue_scripts', 'wp_plugin_enqueue_scripts' );
Do đó nó sẽ chưa gọi file jquery ra
Cách khắc phục
function wp_plugin_enqueue_scripts() {
wp_enqueue_script( 'jquery' );
}
add_action( 'wp_enqueue_scripts', 'wp_plugin_enqueue_scripts' );
Ví dụ 1:
add_action( 'wp_footer', 'my_ajax_without_file' );
function my_ajax_without_file() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ) ?>'; // get ajaxurl
var data = {
'action': 'frontend_action_without_file', // your action name
'variable_name': "Some value" // some additional data to send
};
jQuery.ajax({
url: ajaxurl, // this will point to admin-ajax.php
type: 'POST',
data: data,
success: function (response) {
console.log(response);
}
});
});
</script>
<?php
}
add_action("wp_ajax_frontend_action_without_file" , "frontend_action_without_file");
add_action("wp_ajax_nopriv_frontend_action_without_file" , "frontend_action_without_file");
function frontend_action_without_file(){
echo json_encode($_POST);
wp_die();
}
PreviousMaking a custom control for the Theme CustomizerNextHow to Create Sortable Checkboxes Option in Customizer
Last updated
Was this helpful?