Wordpress Ajax
How to create a wordpress ajax with easiest Example without plugin!
Wordpress Ajax is used to show the content without page load.
Actually some time web page occur lengthy and user have to scroll down the page again and again to see more content on page load so this situation make the user irritate and to avoid this type of problem we have a solution which called Wordpress Ajax.
Let's see how wordpress ajax works?
Here are 2 actions that used in Wordpress Ajax are wp_ajax_nopriv and wp_ajax.
wp_ajax hook allows you to create custom handlers for your own custom AJAX requests. This only fires for logged-in users. If you need to also listen for Ajax requests that don’t come from logged-in users:
wp_ajax_nopriv hook is functionally the same as wp_ajax, however it is used to handle AJAX requests on the front-end for unauthenticated users.
Syntax:
add_action('wp_ajax_nopriv_action_name', 'action_function');
add_action('wp_ajax_action_name', 'action_function');
In the below example we will learn how to show posts by category on load more button click via wordpress ajax?
In this example, we are showing default posts of fruits category by default means if user does not add any category in shortcode parameter. And First we are creating a shortcode to show limited posts and then Jquery code to send ajax request and then action where we will get content by button click.
Calling of below shortcode in posts and pages :
[kamra-cat-filter] || [kamra-cat-filter term="any"]
Calling of above shortcode in files :
<?php echo do_shortcode('[kamra-cat-filter]'); ?>
<?php echo do_shortcode('[kamra-cat-filter term="any"]'); ?>
Demo:
add_shortcode('kamra-category-filter', 'kamraCategoryFilter');
function kamraCategoryFilter($atts){
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
/* Category Listing */
$args = array(
'type' => 'post',
'hide_empty' => 0
);
$categories = get_categories( $args );
$catCount = 1;
$output = '';
$output .= '<div class="cats text-center">';
foreach($categories as $category){
if($catCount == 1) {
$class = 'active';
}
else {
$class = '';
}
if ($category->name != 'Uncategorized') {
$output .= '<a class="'.$class.' moretag" href="#" data-id="'.$category->slug.'">' . esc_html( $category->name ) . '</a>';
}
$catCount++;
}
$output .= '</div>';
$posts_per_page = 5;
/* Specific Category Posts */
$sht_args = shortcode_atts(
array(
'count' => -1,
'term' => 'fruits'
),
$atts, 'kamra-category-filter'
);
if(empty($atts['term'])) {
$term = $sht_args['term'];
}
else {
$term = $atts['term'];
}
$post_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => 'post_date',
'order' => 'DESC',
'posts_per_page' => $posts_per_page,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $term
)
)
);
$querys = new WP_Query($post_args);
if($querys->have_posts()):
$output .= '<div class="container"><div class="row appendix grid m-0">';
while($querys->have_posts()): $querys->the_post();
$output .= '<div class="col-12 col-sm-6 col-md-6 col-lg-4 col-xl-4 p-3 text-center post-complete-data grid-item">';
$output .= '<div class="d-none content position-absolute align-items-center justify-content-center" style="left: .25rem; right: .25rem; top: .25rem; bottom: .25rem; z-index: 9; background: rgba(0,0,0,0.5);">
<a href="' . get_the_permalink() . '" class="text-decoration-none post-title text-capitalize">' . get_the_title() . '</a>
</div>';
$imgUrl = get_the_post_thumbnail_url(get_the_ID(), 'post-thumbnail', '');
$output .= '<div class="img-wrap rounded overflow-hidden">
<img src="' . $imgUrl . '" alt="" class="post-img" style="object-fit: cover; width: 100%; height: 300px;" />
</div>
</div>';
endwhile;
$output .= '</div>';
if($paged < $querys->max_num_pages){
$output .= '<button data-totalPosts="'.$querys->max_num_pages.'" data-cat="' . $term . '" class="d-block load-more-post mx-auto btn btn-sm mt-5 text-decoration-none">Load More Posts</button>';
}
$output .= '</div>';
endif;
return $output;
}
add_action('wp_footer', 'posts_cat_scripts');
function posts_cat_scripts() {
?>
<script type="text/javascript">
jQuery(document).ready( function($) {
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
var ppp = 5;
var page = 2;
var totalPosts = jQuery(".load-more-post").attr("data-totalPosts");
jQuery(document).on("click",".load-more-post", function() {
var obj = jQuery(this);
var cat = jQuery(this).data("cat");
jQuery.post(ajaxUrl, {
action: "load_cat_posts",
page: page,
ppp: ppp,
cat: cat
})
.success(function(posts) {
if(posts) {
if(page == totalPosts) {
obj.remove();
}
page++;
jQuery(".appendix").append(posts).delay(500).masonry();
}
});
});
jQuery(".cats > a").on("click", function(e){
e.preventDefault();
page = 1;
var cat = jQuery(this).data("id");
jQuery.post(ajaxUrl, {
action: "load_cat_posts",
page: page,
ppp: ppp,
cat: cat
})
.success(function(posts) {
page++;
jQuery(".appendix").html(posts).delay(500).masonry();
jQuery(".load-more-post").attr("data-cat",cat);
});
});
});
</script>
<?php
}
function load_cat_posts() {
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 1;
$page = (isset($_POST['page'])) ? $_POST['page'] : 1;
$cat = (isset($_POST['cat'])) ? $_POST['cat'] : 1;
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => 'post_date',
'order' => 'DESC',
'posts_per_page' => $ppp,
'paged' => $page,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $cat
)
)
);
$loop = new WP_Query($args);
$out = '';
if($loop->have_posts()):
while($loop->have_posts()): $loop->the_post();
$out .= '<div class="col-12 col-sm-6 col-md-6 col-lg-4 col-xl-4 p-3 text-center post-complete-data grid-item">';
$out .= '<div class="d-none content position-absolute align-items-center justify-content-center" style="left: .25rem; right: .25rem; top: .25rem; bottom: .25rem; z-index: 9; background: rgba(0,0,0,0.5);">';
$out .= '<a href="' . get_the_permalink() . '" class="text-decoration-none post-title text-capitalize">' . get_the_title() . '</a>';
$out .= '</div>';
$imgUrl = get_the_post_thumbnail_url(get_the_ID(), 'post-thumbnail', '');
$out .= '<div class="img-wrap rounded overflow-hidden">
<img src="' . $imgUrl . '" alt="" class="post-img" style="object-fit: cover; width: 100%;" />
</div>';
$out .= '</div>';
endwhile;
endif;
die($out);
}
add_action('wp_ajax_nopriv_load_cat_posts','load_cat_posts');
add_action('wp_ajax_load_cat_posts','load_cat_posts');
Comments
Post a Comment