ajax load more posts, wp_create_nonce, Votes Post, randon posts (ok)
Ví dụ 1: Không sử dụng wp_create_nonce
Bước 1: Trong file index.php
<?php
/**
* The main template file
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package WordPress
* @subpackage Twenty_Seventeen
* @since 1.0
* @version 1.0
*/
get_header(); ?>
<div class="wrap">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
else :
get_template_part( 'template-parts/post/content', 'none' );
endif;
?>
</main>
<?php
global $wp_query;
if ( $wp_query->max_num_pages > 1 ) echo '<div class="misha_loadmore">More posts</div>';
?>
</div>
</div>
<?php get_footer();
Bước 2:
// Ajax lionel
function misha_my_load_more_scripts() {
global $wp_query;
wp_enqueue_script('jquery');
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/assets/js/myloadmore.js', array('jquery') );
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'posts' => json_encode($wp_query->query_vars),
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages
)
);
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
function misha_loadmore_ajax_handler(){
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1;
$args['post_status'] = 'publish';
query_posts( $args );
if( have_posts() ) :
while( have_posts() ): the_post();
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
endif;
die;
}
add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler');
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler');
Bước 3:
jQuery(document).ready(function($) {
$('.misha_loadmore').click(function(){
var button = $(this);
var data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page' : misha_loadmore_params.current_page
};
$.ajax({
url : misha_loadmore_params.ajaxurl,
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...');
},
success : function( data ){
if( data ) {
button.text( 'More posts' ).prev().before(data);
misha_loadmore_params.current_page++;
if ( misha_loadmore_params.current_page == misha_loadmore_params.max_page )
button.remove();
} else {
button.remove();
}
}
});
});
});
Ví dụ 2: Có sử dụng wp_create_nonce
define("THEMEAJAX",admin_url('admin-ajax.php'));
add_action('wp_ajax_load_posts_by_ajax','load_posts_by_ajax');
add_action('wp_ajax_nopriv_load_posts_by_ajax','load_posts_by_ajax');
function load_posts_by_ajax() {
check_ajax_referer( 'load_more_posts','security' );
$paged = $_POST['page'];
$args = array(
'post_type' => 'post',
'post_status'=>'publish',
'posts_per_page' =>'2',
'paged'=>$paged
);
$my_posts = new WP_Query($args);
if($my_posts->have_posts()) :
?>
<?php while ($my_posts->have_posts()) :$my_posts->the_post() ?>
<h2><?php the_title(); ?></h2>
<?php
endwhile;
endif;
wp_die( );
}
<?php
/**
* The main template file
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package WordPress
* @subpackage Twenty_Seventeen
* @since 1.0
* @version 1.0
*/
get_header(); ?>
<div class="wrap">
<div id="primaryy" class="content-areaa">
<main id="main" class="my-posts" role="mainn">
<?php
if ( have_posts() ) :
/* Start the Loop */
while ( have_posts() ) : the_post();
?>
<h2><?php the_title(); ?></h2>
<?php
the_excerpt();
endwhile;
endif;
?>
</main><!-- #main -->
<a href="javascript:void(0)" id = "loadmore" class="loadmore" data-hue="<?php echo THEMEAJAX;?>">Load More</a>
</div><!-- #primary -->
<script>
var url = jQuery("#loadmore").attr('data-hue');
var page = 2;
jQuery(document).ready(function($) {
$('body').on('click','.loadmore',function() {
var data = {
'action':"load_posts_by_ajax",
'page':page,
'security':'<?php echo wp_create_nonce( "load_more_posts" );?>'
}
$.post(url,data,function(response) {
$('.my-posts').append(response);
page++;
});
});
});
</script>
</div><!-- .wrap -->
<?php get_footer();
Ví dụ 3: Một cách viết khác 3 (Dùng scroll)
<!-- Bước 1 -->
<?php
function shapeSpace_frontend_scripts() {
global $wp_query;
wp_enqueue_style( 'style-name',get_stylesheet_uri());
wp_enqueue_script('jquery');
wp_register_script( 'lionel', get_template_directory_uri() .'/assets/js/custom.js' , array('jquery'), false, true);
wp_localize_script( 'lionel','lionel_loadmore_params' , array(
'ajaxurl' => admin_url('admin-ajax.php'),
'posts' => json_encode($wp_query->query_vars),
'current_page' => get_query_var("paged") ? get_query_var("paged") : 1,
'maxpage' => $wp_query->max_num_pages
)
);
wp_enqueue_script('lionel');
}
add_action('wp_enqueue_scripts', 'shapeSpace_frontend_scripts');
// Lionel 2
function lionel_loadmore_ajax_handler(){
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
query_posts( $args );
if( have_posts() ) :
while( have_posts() ): the_post();
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
endif;
die;
}
add_action('wp_ajax_loadmore', 'lionel_loadmore_ajax_handler');
?>
<!-- Bước 2 -->
<script>
jQuery(function($){
var canBeLoaded = true, // this param allows to initiate the AJAX call only if necessary
bottomOffset = 1080; // the distance (in px) from the page bottom when you want to load more posts
$(window).scroll(function(){
var data = {
'action': 'loadmore',
'query': lionel_loadmore_params.posts,
'page' : lionel_loadmore_params.current_page
};
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
$.ajax({
url : lionel_loadmore_params.ajaxurl,
data:data,
type:'POST',
beforeSend: function( xhr ){
canBeLoaded = false;
},
success:function(data){
if( data ) {
lionel_loadmore_params.current_page++;
if(lionel_loadmore_params.current_page <= lionel_loadmore_params.maxpage) {
$('#main').find('article:last-of-type').after( data );
canBeLoaded = true;
}
}
}
});
}
});
});
</script>
<!-- Bước 3 -->
<?php get_header(); ?>
<div class="wrap">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
endif;
?>
</main>
</div>
</div>
<?php get_footer(); ?>
<!-- Bước 4 file content.php -->
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php
the_title( '<h1 class="entry-title">', '</h1>' );
?>
</header>
<div class="entry-content">
<?php
the_content( sprintf(
__( 'Continue reading<span class="screen-reader-text sss"> "%s"</span>', 'twentyseventeen'), get_the_title()
) );
?>
<!-- Kết quả như này -->
<!--
<p>
<a href="http://localhost/hoang/wordpress/2018/10/21/bai-viet-so-5-2/#more-45" class="more-link">
Continue reading
<span class="screen-reader-text sss"> "Bài viết số 6"</span>
</a>
</p>
-->
</div>
</article>
Ví dụ 4: More ajax toan tap
<?php
add_action( 'wp_enqueue_scripts', 'mfnch_enqueue_styles', 101 );
function mfnch_enqueue_styles() {
wp_enqueue_script( 'my_voter_script_obj', LIONELURICHILD_THEME_URI . '/assets/js/ajaxmp.js',array('jquery'), null, true);
wp_localize_script( 'my_voter_script_obj', 'lionelajax', array( 'url' => admin_url( 'admin-ajax.php' )));
}
add_action('wp_ajax_load_posts_by_ajax','load_posts_by_ajax');
add_action('wp_ajax_nopriv_load_posts_by_ajax','load_posts_by_ajax');
function load_posts_by_ajax() {
$paged = $_POST['page'];
$args = array(
'post_type' => 'post',
'post_status'=>'publish',
'posts_per_page' =>'2',
'paged'=>$paged
);
$my_posts = new WP_Query($args);
if($my_posts->have_posts()) :
?>
<?php while ($my_posts->have_posts()) :$my_posts->the_post() ?>
<li>
<div class="thumnail_list">
<a href="#">
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
<?php the_post_thumbnail(); ?>
</a>
</div>
<?php endif; ?>
</li>
<?php
endwhile;
endif;
wp_die( );
}
jQuery(document).ready(function($) {
$.ajax({
type : 'POST',
data : {'action' : 'load_posts_by_ajax', 'page' : 2},
url : lionelajax.url,
success : function (resp){
var url = lionelajax.url;
var page = 2;
$('body').on('click','.loadmore',function() {
var data = {
'action':"load_posts_by_ajax",
'page':page,
'security':'<?php echo wp_create_nonce( "load_more_posts" );?>'
}
$.post(url,data,function(response) {
$('.contend_manual').append(response);
page++;
});
});
}
});
return false;
});
Ví dụ 5:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sử dụng ajax toàn tập</title>
</head>
<body>
Bước 1: Tạo none & link
<?php
$nonce = wp_create_nonce("my_user_vote_nonce");
$link = admin_url('admin-ajax.php?action=my_user_vote&post_id='.$post->ID.'&nonce='.$nonce);
echo '<a class="user_vote" data-nonce="' . $nonce . '" data-post_id="' . $post->ID . '" href="' . $link . '">vote ...</a>';
?>
Bước 2: Gắn vô hook
<?php
add_action("wp_ajax_my_user_vote", "my_user_vote");
add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");
?>
Bước 3: Viết hàm tương ứng
<?php
function my_must_login() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
echo "You must log in to vote";
die();
}
?>
Chú ý: Ở trong hàm sử dụng die() vì lý do dừng sử lý hook wp_ajax tiếp sau đó bởi lệnh die().
Mẫu 2: Dùng Ajax dưới dạng $.ajax();
<script>
var post_id = 1;
var nonce = wp_create_nonce("my_user_nonce");
$.ajax({
type : "post",
dataType : "json",
url : '<?php echo htmlspecialchars(admin_url('admin-ajax.php'), ENT_QUOTES); ?>',
data : {action: "my_user", post_id : post_id, nonce: nonce},
success: function(response) {
console.log(response);
}
}) ;
</script>
<!-- Chúng ta chèn thêm thư viện jQuery -->
<h1>Cách 1: Hướng dẫn đầy đủ sử dụng file js bên ngoài</h1>
<!-- Bước 1 -->
<?php
add_action('wp_enqueue_scripts', 'pw_load_scripts');
function pw_load_scripts() {
wp_enqueue_script('pw-script', get_template_directory_uri() . '/js/my_js.js');
wp_localize_script('pw-script', 'lionelajax', array(
'url' => admin_url('admin-ajax.php')
)
);
}
add_action("wp_ajax_dvd_action", "my_user_vote");
add_action("wp_ajax_nopriv_dvd_action", "my_user_vote");
function my_user_vote() {
echo $_POST['data'];
die();
}
?>
<!-- Bước 2: Nội dung file my_js.js-->
<script>
jQuery(document).ready(function($) {
$.ajax({
type : 'POST',
data : {'action' : 'dvd_action', 'data' : 'Dữ liệu được gửi lên sever'},
url : lionelajax.url,
success : function (resp){
console.log(resp);
}
});
return false;
});
</script>
<h1>Cách 2: Hướng dẫn đầy đủ sử dụng file js bên ngoài</h1>
<!-- Bước 1 -->
<?php
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'my_voter_script_obj', get_template_directory_uri().'/js/my_js.js' );
wp_localize_script( 'my_voter_script_obj', 'lionelajax', array( 'url' => admin_url( 'admin-ajax.php' )));
}
add_action("wp_ajax_dvd_action", "my_user_vote");
add_action("wp_ajax_nopriv_dvd_action", "my_user_vote");
function my_user_vote() {
echo $_POST['data'];
die();
}
?>
<!-- Bước 2: Nội dung file my_js.js-->
<script>
jQuery(document).ready(function($) {
$.ajax({
type : 'POST',
data : {'action' : 'dvd_action', 'data' : 'Dữ liệu được gửi lên sever'},
url : lionelajax.url,
success : function (resp){
console.log(resp);
}
});
return false;
});
</script>
</body>
</html>
Ví dụ 6: Votes Post
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Votes Post</title>
</head>
<body>
<!-- Bước 1: -->
<?php
if(!get_post_meta(4004,"votes",true)){
add_post_meta(4004,"votes",0);
};
$votes = get_post_meta(4004, "votes", true);
$votes = ($votes == "") ? 0 : $votes;
?>
This post has <div id='vote_counter'><?php echo $votes ?></div> votes<br>s
<?php
$nonce = wp_create_nonce("my_user_vote_nonce");
$link = admin_url('admin-ajax.php?action=my_user_vote&post_id=4004&nonce='.$nonce);
echo '<a class="user_vote" data-nonce="' . $nonce . '" data-post_id=4004 href="' . $link . '">vote for this article</a>';
?>
<!-- Bước 2: -->
<?php
add_action("wp_ajax_my_user_vote", "my_user_vote");
add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");
function my_user_vote() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
function my_must_login() {
echo "You must log in to vote";
die();
}
?>
</body>
</html>
Ví dụ 6: randon posts
Bước chuẩn bị: Chuẩn bị nội dung của randon posts
Bước 1: Nạp file supriced.js
wp_enqueue_script( 'twentyseventeen-g', get_theme_file_uri( '/inc/supriced.js' ), array( 'jquery' ), '1.0', true );
Bước 2: Bạn tạo copy code sau
<p><a href="#" id="suprised">Lorem</a></p>
<div id="result">
<?php
get_template_part( 'randon');
?>
</div>
Chú ý: Bạn có thể sử dụng giống WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)) . '/jquery.ajax.readmore.js',
để nạp file
randon.php
<?php
/*
Template name: Randon Posts
*/
?>
<?php
query_posts('posts_per_page=3&orderby=rand');
if(have_posts()) :
while(have_posts()) : the_post();
the_excerpt();
endwhile;
else:
echo "Không có bài viết";
endif;
wp_reset_query();
?>
jQuery(document).ready(function($) {
$('#suprised').click(function() {
var url = "http://localhost/success/new4/more-content";
$("#result").load(url);
return false;
});
});
Hướng dẫn của Demon Warlock
jQuery(document).ready(function($) {
var url = $('#morepostt').attr('data-hue');
$('#morepostt').click(function(event) {
$('#result').load(url);
});
return false;
});
index.php
<?php
/**
* The main template file
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package WordPress
* @subpackage Twenty_Seventeen
* @since 1.0
* @version 1.0
*/
get_header(); ?>
<div class="wrap" style="max-width: 1000px;">
<?php if ( is_home() && ! is_front_page() ) : ?>
<header class="page-header">
<h1 class="page-title"><?php single_post_title(); ?></h1>
</header>
<?php else : ?>
<header class="page-header">
<h2 class="page-title"><?php _e( 'Posts', 'twentyseventeen' ); ?></h2>
</header>
<?php endif; ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php get_template_part('randon'); ?>
</main><!-- #main -->
<a id="morepostt" href="javascript:void(0)" data-hue='http://localhost/success/new4/more-content'>More Post</a>
<div id="result"></div>
</div><!-- #primary -->
</div><!-- .wrap -->
<?php get_footer();
randon.php
<?php
/*
Template Name: More Content
*/
?>
<?php
query_posts('posts_per_page=3&orderby=rand');
if(have_posts()) :
while(have_posts()) : the_post();
the_excerpt();
endwhile;
else:
echo "Không có bài viết";
endif;
wp_reset_query();
?>
Previouscách sử dụng wp_localize_script trong mẫu trang tùy chỉnh (ok)NextHoàn thiện chức năng vote cho bài viết full (ok)
Last updated