a). Short code callback function to display initial posts at WordPress active theme functions.php file. Ex : /wp-content/themes/twentyseventeen/functions.php
* initial posts dispaly
*/
function script_load_more($args = array()) {
//initial posts load
echo '<div id="ajax-primary" class="content-area">';
echo '<div id="ajax-content" class="content-area">';
ajax_script_load_more($args);
echo '</div>';
echo '<a href="#" id="loadMore" data-page="1" data-url="'.admin_url("admin-ajax.php").'" >Load More</a>';
echo '</div>';
}
1 2 3 4 | /* * create short code. */ add_shortcode('ajax_posts', 'script_load_more'); |
2: a). Create a callback function to to load posts at WordPress active theme functions.php file.Ex : /wp-content/themes/twentyseventeen/functions.php
/*
* load more script call back
*/
function ajax_script_load_more($args) {
//init ajax
$ajax = false;
//check ajax call or not
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$ajax = true;
}
//number of posts per page default
$num =5;
//page number
$paged = $_POST['page'] + 1;
//args
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' =>$num,
'paged'=>$paged
);
//query
$query = new WP_Query($args);
//check
if ($query->have_posts()):
//loop articales
while ($query->have_posts()): $query->the_post();
//include articles template
include 'ajax-content.php';
endwhile;
else:
echo 0;
endif;
//reset post data
wp_reset_postdata();
//check ajax call
if($ajax) die();
}
c).Create a ajax action hook to call “ajax_script_load_more” function to to load posts at WordPress active theme functions.php file. Ex : /wp-content/themes/twentyseventeen/functions.php
4 5 | /* * load more script ajax hooks */ add_action('wp_ajax_nopriv_ajax_script_load_more', 'ajax_script_load_more'); add_action('wp_ajax_ajax_script_load_more', 'ajax_script_load_more'); * enqueue js script */ add_action( 'wp_enqueue_scripts', 'ajax_enqueue_script' ); /* * enqueue js script call back */ function ajax_enqueue_script() { wp_enqueue_script( 'script_ajax', get_theme_file_uri( '/js/script_ajax.js' ), array( 'jquery' ), '1.0', true ); }
a). Load posts when user clicks the Load More button
|
No comments:
Post a Comment