I found a solution how to get a load more button that displays more content on click, but it was for posts, I want to make it work for my custom post type 'Klanten'.
I tried editing the code to match my post type, but I get an error: "Undefined index: offset"
functions.php
wp_enqueue_script( 'dfib-theme-custom', get_template_directory_uri() .'/js/custom.js', array('jquery') );
wp_localize_script( 'dfib-theme-custom', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
add_action( 'wp_ajax_load_more_posts', 'load_more_posts' );
add_action( 'wp_ajax_nopriv_load_more_posts', 'load_more_posts' );
function load_more_posts(){
global $post;
$args = array('post_type'=>'klanten', 'posts_per_page'=> 4, 'offset'=> $_POST['offset']);
$rst=[];
$query = new WP_Query($args);
if($query->have_posts()):
while($query->have_posts()):$query->the_post();
$rst[] = $post;
endwhile;
wp_reset_postdata();
$offset = $_POST['offset']+4;
endif;
wp_send_json_success(array('klanten'=>$rst, 'offset'=>$offset));
}
custom.js
$('#load_more_posts').on('click', function(e){
console.log('hi');
e.preventDefault();
var $offset = $(this).data('offset');
console.log('var'+$offset);
$.ajax({
method: 'POST',
url: ajax_object.ajax_url,
type: 'JSON',
data: {
offset: $offset,
action: 'load_more_posts'
},
success:function(response){
console.log(response);
$('#load_more_posts').data('offset', parseInt(response.data.offset));
}
});
})
php-file
$query = new WP_Query( array(
'post_type' => 'klanten',
'posts_per_page' => 4,
'offset' => 0,
'paged' => 1,
'order' => 'ASC',
'orderby' => 'rand',
) );
if ( $query->have_posts() ) { ?>
<div class="klanten__wrapper">
<?php
while ( $query->have_posts() ) :
$query->the_post();
?>
<div class="logo__wrapper">
<img class="klant__logo" src="<?php the_post_thumbnail_url(); ?>">
</div>
<?php endwhile; ?>
<div id="load_more_posts" class="loadmore">Load More...</div>
</div>
<?php
wp_reset_postdata();
return ob_get_clean();
}
Console log
I want to show 4 logo's (elements), and load 4 more each time someone clicks the loadmore button
Replace this
<div id="load_more_posts" class="loadmore" data-offset="4">Load More...</div>
You need to return ajax data with logo array and then append data like below code.
AJAX call
$('#load_more_posts').on('click', function(e){
console.log('hi');
e.preventDefault();
var $offset = $(this).data('offset');
console.log('var'+$offset);
$.ajax({
method: 'POST',
url: ajax_object.ajax_url,
type: 'JSON',
data: {
offset: $offset,
action: 'load_more_posts'
},
success:function(response){
console.log(response);
var html = "";
$(response.data.klanten).each(function(index,value) {
html += '<div class="logo__wrapper"> <img class="klant__logo" src="'+value.post_thumbnail+'"></div>'
});
$('.logo_wrapper').append(html);
$('#load_more_posts').data('offset',
parseInt(response.data.offset));
}
});
})
HTML Code
<div class="klanten__wrapper">
<div class="logo_wrapper">
<?php
while ( $query->have_posts() ) :
$query->the_post();
?>
<div class="logo__wrapper">
<img class="klant__logo" src="<?php the_post_thumbnail_url(); ?>">
</div>
<?php endwhile; ?>
<div>
<div id="load_more_posts" class="loadmore">Load More...</div>
</div>
function.php
wp_enqueue_script( 'dfib-theme-custom', get_template_directory_uri() .'/js/custom.js', array('jquery') );
wp_localize_script( 'dfib-theme-custom', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
add_action( 'wp_ajax_load_more_posts', 'load_more_posts' );
add_action( 'wp_ajax_nopriv_load_more_posts', 'load_more_posts' );
function load_more_posts(){
global $post;
$args = array('post_type'=>'klanten', 'posts_per_page'=> 4, 'offset'=> $_POST['offset']);
$rst=[];
$query = new WP_Query($args);
if($query->have_posts()):
while($query->have_posts()):$query->the_post();
$rst[] = $post;
$post_thumbnail = get_the_post_thumbnail($post->id);
$rst['post_thumbnail'] = $post_thumbnail;
endwhile;
wp_reset_postdata();
$offset = $_POST['offset']+4;
endif;
wp_send_json_success(array('klanten'=>$rst, 'offset'=>$offset));
}
I got help from a colleague and he figured it out. I added this in my js-file (jQuery)
// Counter for logos
var logoCount = $('.logo__wrapper').length;
var counter = 12;
// Show only first 12 logos
$('.logo__wrapper:nth-of-type(1n+13)').addClass('is-hidden');
// Load more logos button click
$('#load_more_posts').on('click', function (e) {
// Loop hidden logo's
$('.logo__wrapper.is-hidden').each(function (i) {
// Hide button if no more logo's
if (counter++ === logoCount) {
$('#load_more_posts').hide();
$('.loadmore__end').toggle();
}
// Show next 12 logos
if (i < 12) {
$(this).removeClass('is-hidden');
}
// Break loop after 12 logos
else {
return false;
}
});
});
Related
I've now been scratching my head about this for several days and need some pointers.
I'm making a custom theme totally from scratch for a WooCommerce site and now I'm trying to get the cart functionality to work. I'm stuck at trying to have buttons (+/-) for updating the quantity of a product item in the cart.
The problem to me seems to be that the WC() I use inside functions.php is not the same instance as the current frontend-session, or something among those lines. At least my thought for now.
If I've debugged correctly the WC()->cart->set_quantity($cart_item_key, 0) gives no error (if using number 0), all other numbers gives '500 (Internal Server Error)'. But even with 0 quantity in cart is never changed nonetheless.
I've enqueued the scripts correctly so the AJAX function call executes fine when the button is clicked.
Here's my HTML and PHP (simplified)
<div class="cart-items">
<?php foreach(WC()->cart->get_cart() as $cart_item_key => $cart_item) : ?>
<div class="cart-item">
<div class="quantity" id="cart-qty-<?php echo $cart_item_key ?>">
<button class="minus" id="cart-subtract"
onclick="updateCartQuantity('<?php echo $cart_item_key ?>', '<?php echo $cart_item['quantity'] ?>', -1)">-</button>
<p><?php echo $cart_item['quantity'] ?></p>
<button class="plus" id="cart-add">+</button>
</div>
</div>
<? endforeach; ?>
</div>
Here's my JS (inside a file called shopping-ajax.js)
function updateCartQuantity(cart_item_key, current_qty, value) {
function qty_cart() {
jQuery.ajax({
type: "POST",
url: my_ajax_object.ajax_url,
data: {
action: "update_cart",
hash: cart_item_key,
quantity: current_qty,
value: value,
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
},
});
}
qty_cart();
}
Here's my PHP function (inside functions.php)
function updateCartQuantity(){
$cart_item_key = $_REQUEST['cart_item_key'];
$quantity = $_REQUEST['quantity'];
$value = $_REQUEST['value'];
WC()->cart->set_quantity($cart_item_key, $quantity + $value);
echo $quantity + $value;
wp_die();
}
add_action( 'wp_ajax_nopriv_update_cart', 'updateCartQuantity' );
add_action( 'wp_ajax_update_cart', 'updateCartQuantity' );
A massive thanks for any help or pointer in advance!
You should manage product qty according to the qty input box(change qty).
My JS:
location: theme directory -> js -> custom.js
jQuery( function( $ ) {
$( document ).on( 'change', 'input.qty', function() {
var $thisbutton = $(this);
var item_hash = $( this ).attr( 'name' ).replace(/cart\[([\w]+)\]\[qty\]/g, "$1");
var item_quantity = $( this ).val();
var currentVal = parseFloat(item_quantity);
$.ajax({
type: 'POST',
url: cart_qty_ajax.ajax_url,
data: {
action: 'my_cart_qty',
hash: item_hash,
quantity: currentVal
},
success: function(response) {
jQuery(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]);
//jQuery(document.body).trigger('update_checkout');
}
});
});
});
fuctions.php -
Setup Enqueue Ajax Scripts:
function enqueue_cart_qty_ajax() {
wp_register_script( 'my_cart_qty-ajax-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '', true );
wp_localize_script( 'my_cart_qty-ajax-js', 'cart_qty_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'my_cart_qty-ajax-js' );
}
add_action('wp_enqueue_scripts', 'enqueue_cart_qty_ajax');
Ajax call -
function ajax_my_cart_qty() {
// Set item key as the hash found in input.qty's name
$cart_item_key = $_POST['hash'];
// Get the array of values owned by the product we're updating
$threeball_product_values = WC()->cart->get_cart_item( $cart_item_key );
// Get the quantity of the item in the cart
$threeball_product_quantity = apply_filters( 'woocommerce_stock_amount_cart_item', apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9\.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)) ), $cart_item_key );
// Update cart validation
$passed_validation = apply_filters( 'woocommerce_update_cart_validation', true, $cart_item_key, $threeball_product_values, $threeball_product_quantity );
// Update the quantity of the item in the cart
if ( $passed_validation ) {
WC()->cart->set_quantity( $cart_item_key, $threeball_product_quantity, true );
}
// Refresh the page
echo do_shortcode( '[woocommerce_cart]' );
die();
}
add_action('wp_ajax_my_cart_qty', 'ajax_my_cart_qty');
add_action('wp_ajax_nopriv_my_cart_qty', 'ajax_my_cart_qty');
While the search form works, I need help fixing the problem that occurs when the form is empty after having been typed into.
What I mean is this:
If you start typing a search query, you start to get results. This part works fine.
But if you, while / after typing, remove the text from the search form - you get a list of ALL products.
It should only show results if and when typing and show nothing if and when empty.
Fix:
After applying a modified version of the solution offered and provided by Terminator-Barbapapa as per below, it works as intended.
The code below might not be 100% correct, but it works.
The code so far:
add_shortcode('live_search', 'live_search_function');
function live_search_function() { ?>
<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>
<div id="productfetch"></div>
<?php
}
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() { ?>
<script type="text/javascript">
function fetch() {
if( document.getElementById('keyword').value.trim().length == 0 ) {
jQuery('#productfetch').html('');
} else {
jQuery.ajax( {
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#productfetch').html( data );
}
});
}
}
</script>
<?php
}
add_action('wp_ajax_data_fetch' , 'product_fetch');
add_action('wp_ajax_nopriv_data_fetch','product_fetch');
function product_fetch() {
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'product' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><?php the_title();?></h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
You can add a check in your fetch() function to see if your input field is empty. If so, clear the datafetch div, else run your AJAX.
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() { ?>
<script type="text/javascript">
function fetch() {
if( document.getElementById('keyword').value.trim().length == 0 ) {
jQuery('#productfetch').html('');
} else {
jQuery.ajax( {
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#productfetch').html( data );
}
});
}
}
</script>
<?php
}
I try to build a car search plugin, with 3 category levels.
Like: 1 row = Maincat, 2 row = Subcat, 3 row = Subsubcat...
Here is an example of what i want to do:
https://www.aez-wheels.com/3DKonfigurator/index.php?lcs=onz2sm13at&lng=en
in my code the first level appears and the second level loads. but the third level is not loading.
I Think the problem is, that the second row is created dynamicaly.
Can somebody tell me where i have a wrong code?
// Loading WordPress hooks
function __construct()
{
add_action( 'avada_after_header_wrapper', array($this, 'llm_car_conf_list') );
// Register ajax action
add_action( 'wp_ajax_get_cat', array($this, 'getCat') );
// Register ajax action for non loged in user
add_action('wp_ajax_nopriv_get_cat', array($this, 'getCat') );
}
// function for the maincat
function llm_car_conf_list() {
if ( is_front_page() ) {?>
<div class="llm_car_container">
<div class="car_wrapper">
<div class="car_row">
<div class="car_title"><h2>1. Fahrzeug wählen</h2></div>
<ul id="maincat" class="car_conf"><?php
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'parent' => 0
));
foreach ( $categories as $category ) {
printf( '<li class="car_list_item"><a id="%1$s">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
}
?></ul></div>
// Jquery to load first subcat
<script type="text/javascript">
(function($){
$("#maincat li").click(function(){
$("#second_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#second_row").append(data);
}
});
});
})(jQuery);
</script>
<div class="car_row">
<div class="car_title"><h2>2. Typ wählen</h2></div>
<ul id="second_row" class="car_conf"></ul>
</div>
// Jquery to load subsubcat
<script type="text/javascript">
(function($){
$("#second_row li").click(function(){
$("#third_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#third_row").append(data);
}
});
});
})(jQuery);
</script>
<div class="car_row">
<div class="car_title"><h2>3. Jahrgang wählen</h2></div>
<ul id="third_row" class="car_conf"></ul>
</div>
</div>
</div>
<?php
}
}
// Function to load the subcats
function getCat() {
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'child_of' => $_POST['cat_id'],
'parent' => $_POST['cat_id']
));
foreach ( $categories as $category ) {
printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
}
die();
}
Here is my full code, that works in my plugin
<?php
defined('ABSPATH') or die("Thanks for visting");
if ( ! class_exists( 'frontendAjaxDdown' ) ):
class frontendAjaxDdown
{
// Loading WordPress hooks
function __construct()
{
add_action( 'avada_after_header_wrapper', array($this, 'llm_car_conf_list') );
// Register ajax action
add_action( 'wp_ajax_get_cat', array($this, 'getCat') );
add_action( 'wp_ajax_get_subcat', array($this, 'getSubCat') );
add_action( 'wp_ajax_get_subsubcat', array($this, 'getSubSubCat') );
// Register ajax action for non loged in user
add_action('wp_ajax_nopriv_get_cat', array($this, 'getCat') );
add_action('wp_ajax_nopriv_get_subcat', array($this, 'getSubCat') );
add_action('wp_ajax_nopriv_get_subsubcat', array($this, 'getSubSubCat') );
}
function llm_car_conf_list() {
if ( is_front_page() ) {?>
<div class="llm_car_container">
<div class="car_wrapper">
<div class="car_row">
<div class="car_title"><h2>1. Fahrzeug wählen</h2></div>
<ul id="maincat" class="car_conf"><?php
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'parent' => 0
));
foreach ( $categories as $category ) {
printf( '<li class="car_list_item"><a id="%1$s"><img src="http://climair-schweiz.ch.185-117-169-242.srv201.webpreview.ch/wp-content/uploads/carbrands/%2$s.png" width="20px">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
} ?>
</ul>
</div>
<script type="text/javascript">
(function($){
$("#maincat li").click(function(){
$("#second_row, #third_row, #fourth_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#second_row").append(data);
}
});
});
})(jQuery);
</script>
<div class="car_row">
<div class="car_title"><h2>2. Model wählen</h2></div>
<ul id="second_row" class="car_conf"></ul>
</div>
<div class="car_row">
<div class="car_title"><h2>3. Baujahr | Typ wählen</h2></div>
<ul id="third_row" class="car_conf"></ul>
</div>
<div class="car_row">
<div class="car_title"><h2>4. Form | Türen wählen</h2></div>
<ul id="fourth_row" class="car_conf"></ul>
</div>
</div>
</div> <?php
}
}
function getCat() {
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'child_of' => $_POST['cat_id'],
'parent' => $_POST['cat_id']
));
foreach ( $categories as $category ) {
printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
} ?>
<script type="text/javascript">
(function($){
$("#second_row li").click(function(){
$("#third_row, #fourth_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_subcat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#third_row").append(data);
}
});
});
})(jQuery);
</script> <?php
die();
}
function getSubCat() {
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'child_of' => $_POST['cat_id'],
'parent' => $_POST['cat_id']
));
foreach ( $categories as $category ) {
printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
}
?> <script type="text/javascript">
(function($){
$("#third_row li").click(function(){
$("#fourth_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_subsubcat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#fourth_row").append(data);
}
});
});
})(jQuery);
</script> <?php
die();
}
function getSubSubCat() {
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'child_of' => $_POST['cat_id'],
'parent' => $_POST['cat_id']
));
foreach ( $categories as $category ) {
printf( '<li class="car_list_item">%2$s</li>',
esc_url( get_category_link( $category->term_id ) ),
esc_html( $category->cat_name )
);
}
die();
}
}
endif;
new frontendAjaxDdown();
?>
I am trying to create a search functionality with AJAX so it will load posts. It currently does not show the results.
I took this code from another post and played around with it as the completed code was sent privately.
Any help would be greatly appreciated.
functions.php file code
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><?php the_title();?></h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}}
Script (in functions.php)
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
html
<input type="text" name="keyword" id="keyword" onkeyup="fetch()">
<div id="datafetch">Search results will appear here</div>
You might want to update the method name to 'POST' as javascript is case sensitive
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
You also might want to do an async call which needs callback as above approach will do synchronous call. Check this answer for callback approach
jQuery: Return data after ajax call success
there are some typos in your code like an extra } and a mising } later in php code. Please try:
functions.php
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><?php the_title();?></h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch_search() {
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
html
<input type="text" name="keyword" id="keyword" onkeyup="fetch_search()">
<div id="datafetch">Search results will appear here</div>
I'm trying to create a sequence of events as described below:
1) The user would click on .post-link which would scroll the page to the top if it isn't there already.
2) The #project-container would open up revealing the #loading-animation.
3) The post would load via Ajax.
Right now, when I click on .post-link, everything seems to happen at once. How can I format the code below to make sure that one event happens after another one finishes?
Essentially, this is what I'm trying to recreate. When you click on a post, notice how the hidden container opens up to reveal the loading animation, and then once the content has loaded, it opens up to display the content.
JS
$('.post-link').click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop : 0
},500, function() {
$('#loading-animation').show();
});
var post_id = $(this).attr('rel');
var ajaxURL = site.ajaxurl;
$.ajax({
type: 'POST',
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
success: function(response) {
$('#project-container').html(response);
$('#loading-animation').hide();
return false;
}
});
});
HTML
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div id="project-container">
<img id="loading-animation" src="http://i.imgur.com/5RMfW8P.gif" style="display:none">
</div>
<!-- Start the loop -->
<?php $home_query = new WP_Query('post_type=projects');
while($home_query->have_posts()) : $home_query->the_post(); ?>
<a class="post-link" href="#" rel="<?php the_ID(); ?>">
<article id="post-<?php the_ID(); ?>">
<div class="post-info">
<h1 class="entry-title"><?php the_title(); ?></h1>
</div>
<?php the_post_thumbnail( "home-thumb", array( 'class' => 'grayscale grayscale-fade') ); ?>
</article><!-- #post-## -->
</a>
<?php endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>
</main><!-- #main -->
</div><!-- #primary -->
PHP
/**
* Enqueue scripts and styles.
*/
function starter_scripts() {
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', includes_url( '/js/jquery/jquery.js' ), false, NULL, true );
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'jquery-effects-core');
wp_enqueue_style( 'starter-style', get_stylesheet_uri() );
wp_enqueue_script( 'gray', get_template_directory_uri() . '/js/min/jquery.gray.min.js', array('jquery'), '', true );
wp_enqueue_script( 'includes', get_template_directory_uri() . '/js/min/includes.min.js', array('jquery'), '', true );
wp_localize_script( 'includes', 'site', array(
'theme_path' => get_template_directory_uri(),
'ajaxurl' => admin_url('admin-ajax.php')
)
);
}
add_action( 'wp_enqueue_scripts', 'starter_scripts' );
/**
* Return the post content to the AJAX call
*/
function my_load_ajax_content () {
$args = array(
'p' => $_POST['post_id'],
'post_type' => 'projects'
);
$post_query = new WP_Query( $args );
while( $post_query->have_posts() ) : $post_query->the_post(); ?>
<div class="post-container">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
<?php the_content(); ?>
</div><!-- #post-## -->
<?php
endwhile;
exit;
}
add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' );
add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' );
After loading the first post, your #loading-animation is being removed and you cannot interact with it anymore.
Try to load your ajax content into another wrapper element within the #project-container
HTML
<div id="project-container">
<img id="loading-animation" src="http://i.imgur.com/5RMfW8P.gif" style="display:none">
<div class="ajax-wrapper"></div>
</div>
JS
[...]
success: function(response) {
$('#project-container .ajax-wrapper').html(response);
$('#loading-animation').hide();
return false;
}
[...]
You have to put your Ajax call into the .show() function for chaining animations.
http://api.jquery.com/show/
$('.post-link').click(function(e) {
e.preventDefault();
var post_id = $(this).attr('rel');
var ajaxURL = site.ajaxurl;
$('html, body').animate({
scrollTop : 0
},500, function() {
$('#loading-animation').show(500, function() {
$.ajax({
type: 'POST',
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
success: function(response) {
$('#project-container').html(response);
$('#loading-animation').hide();
return false;
}
});
});
});
});