This is my loop of posts:
<?php
$query_masonry = new WP_Query(array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3
));
if ($query_masonry->have_posts()) :
while ($query_masonry->have_posts() ) : $query_masonry->the_post();
get_template_part( 'content', get_post_format() );
endwhile;
else :
get_template_part( 'content', 'none' );
endif;
wp_reset_postdata();
?>
at below, I have this:
<button id="load-more">Load more</button>
How I can load 3 more posts with ajax just clicking at the button "Load more"?
I've tried a lot of plugins, but unsuccessful.
Any one help me?
I want update my code, ajax load post with fetch api:
PHP code:
// Enqueue script.
wp_enqueue_script( 'ajax-load-post' );
wp_localize_script(
'ajax-load-post',
'ajax_load_post_data',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajax_nonce' => wp_create_nonce( 'ajax_load_post' ),
)
);
// Ajax handle.
add_action( 'wp_ajax_load_post', 'ajax_load_post' );
add_action( 'wp_ajax_nopriv_load_post', 'ajax_load_post' );
function ajax_load_post() {
check_ajax_referer( 'ajax_load_post', 'ajax_nonce' );
$post_query = new WP_Query(
array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3,
)
);
ob_start();
if ( $post_query->have_posts() ) {
while ( $post_query->have_posts() ) {
$post_query->the_post();
echo get_the_title() . '<br>';
}
} else {
echo 'No posts found!';
}
$response['content'] = ob_get_clean();
wp_send_json_success( $response );
}
JS code:
// In js file.
document.addEventListener(
'load',
function() {
var data = {
action: 'load_post',
ajax_nonce: ajax_load_post_data.ajax_nonce,
};
data = new URLSearchParams( data ).toString();
var request = new Request(
ajax_load_post_data.ajax_url,
{
method: 'POST',
body: data,
credentials: 'same-origin',
headers: new Headers(
{
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
}
)
}
);
fetch( request )
.then(
function( res ) {
if ( 200 !== res.status ) {
console.log( 'Status Code: ' + res.status );
throw res;
}
return res.json();
}
).then(
function( json ) {
if ( ! json.success ) {
return;
}
console.log( 'Json data:', json.data );
}
).catch(
function( err ) {
console.log( err );
}
).finally(
function() {
console.log( 'All Done!' );
}
);
}
);
Related
Am trying to get the shipping packages with ajax but its always returning empty value.
same issue while trying to call get the zones with: WC_Shipping_Zones::get_zones();
am using the same code in woocommerce_checkout_before_order_review and its working without any issue!
function jsforwp_add_like() {
check_ajax_referer( 'jsforwp_likes_nonce' );
$packages = WC()->shipping->get_packages();
if(empty($packages)){
$check = 'empty';
}else{
$check = $packages;
}
$success = true;
if( true == $success ) {
$response['type'] = 'success';
$response['zone'] = $check;
}
$response = json_encode( $response );
echo $response ;
die();
}
add_action( 'wp_ajax_jsforwp_add_like', 'jsforwp_add_like' );
add_action( 'wp_ajax_nopriv_jsforwp_add_like', 'jsforwp_add_like' );
My javascript
add_action('wp_footer','my_custom_ajax');
function my_custom_ajax(){
?>
<script>
(function($){
$( document.body ).on( 'updated_checkout', function(){
$.ajax({
type : 'post',
dataType : 'json',
url : jsforwp_globals.ajax_url,
data : {
action: 'jsforwp_add_like',
_ajax_nonce: jsforwp_globals.nonce
},
success: function( response ) {
if( 'success' == response.type ) {
console.log( response );
}
else {
console.log( 'Something went wrong, try logging in!' );
}
}
});
} );
} )( jQuery );
</script>
<?php
}
returned value
{type: "success", zone: "empty"}
I'm trying to add more than one fee to the order total amount checkout using ajax.
So far, the first fee, insurance_shipping_fee, is working correctly, but when checking the second one, premium_gift_box, I receive a 400 error ("xxx.com/wp-admin/admin-ajax.php").
Any ideas on why?
Any help appreciated
This is the full code:
// Calculate insurance fee
function as_calculate_insurance_fee() {
$shipping_country = WC()->customer->get_shipping_country();
$cart_subtotal = WC()->cart->subtotal;
$cart_subtotal_rounded = ceil($cart_subtotal / 100) * 100;
if($shipping_country == 'AU') {
if($cart_subtotal <= 5000) $insurance_fee = $cart_subtotal_rounded/100 + 1;
} else {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
if ($chosen_shipping == 'free_shipping:12' || $chosen_shipping == 'starshipit_4') {
if($cart_subtotal <= 5000) $insurance_fee = $cart_subtotal_rounded/100 * 3;
} else if($chosen_shipping == 'starshipit_5') {
$insurance_fee = ($cart_subtotal_rounded - 1000)/100 * 3 + 25;
}
}
return $insurance_fee;
}
// Add a Shipping Insurance checkbox field
function add_custom_checkout_checkbox() {
$insurance_fee = as_calculate_insurance_fee();
if( WC()->session->get('enable_fee') ) $checked = true;
else $checked = false;
woocommerce_form_field( 'insurance_fee', array(
'type' => 'checkbox',
'label' => __('<span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">'.get_woocommerce_currency().' </span>'.$insurance_fee.'</bdi></span>'),
'class' => array( 'form-row-wide' ),
), $checked );
}
add_action( 'as_review_order_after_shipping', 'add_custom_checkout_checkbox', 20 );
// Add Signature Gift Box checkbox field
function add_custom_checkout_checkbox_2() {
if( WC()->session->get('enable_fee_2') ) $checked = true;
else $checked = false;
woocommerce_form_field( 'premium_giftbox_fee', array(
'type' => 'checkbox',
'label' => __('<span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">'.get_woocommerce_currency().' </span>9</bdi></span>'),
'class' => array( 'form-row-wide' ),
), $checked );
}
add_action( 'as_review_order_before_shipping', 'add_custom_checkout_checkbox_2', 20 );
// Add custom fees
function custom_fee( $cart ) {
// Only on checkout
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
return;
$insurance_fee = as_calculate_insurance_fee();
if( WC()->session->get('enable_fee') )
$cart->add_fee( __( 'Insurance fee', 'woocommerce'), $insurance_fee );
if( WC()->session->get('enable_fee_2') )
$cart->add_fee( __( 'Siganture Gift Box fee', 'woocommerce'), 9 );
}
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee', 20, 1 );
// Remove "(optional)" label on checkbox field
function remove_order_comments_optional_fields_label( $field, $key, $args, $value ) {
// Only on checkout page for Order notes field
if( ( 'insurance_fee' === $key || 'premium_giftbox_fee' === $key ) && is_checkout() ) {
$optional = ' <span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
$field = str_replace( $optional, '', $field );
}
return $field;
}
add_filter( 'woocommerce_form_field' , 'remove_order_comments_optional_fields_label', 10, 4 );
// jQuery - Ajax script
function checkout_fees_script() {
// Only on Checkout
if( is_checkout() && ! is_wc_endpoint_url() ) :
if( WC()->session->__isset('enable_fee') )
WC()->session->__unset('enable_fee');
if( WC()->session->__isset('enable_fee_2') )
WC()->session->__unset('enable_fee_2');
?>
<script type="text/javascript">
jQuery( function($){
if (typeof wc_checkout_params === 'undefined')
return false;
$('form.checkout').on('change', 'input[name=insurance_fee]', function(e){
var fee = $(this).prop('checked') === true ? '1' : '';
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'enable_fee',
'enable_fee': fee,
},
success: function (result) {
$('body').trigger('update_checkout');
},
});
});
$('form.checkout').on('change', 'input[name=premium_giftbox_fee]', function(e){
var fee2 = $(this).prop('checked') === true ? '1' : '';
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'enable_fee_2',
'enable_fee_2': fee2,
},
success: function (result) {
$('body').trigger('update_checkout');
},
});
});
});
</script>
<?php
endif;
}
add_action( 'wp_footer', 'checkout_fees_script' );
// Get Ajax request and saving to WC session
function get_enable_fee() {
if ( isset($_POST['enable_fee']) ) {
WC()->session->set('enable_fee', ($_POST['enable_fee'] ? true : false) );
}
if ( isset($_POST['enable_fee_2']) ) {
WC()->session->set('enable_fee_2', ($_POST['enable_fee_2'] ? true : false) );
}
die();
}
add_action( 'wp_ajax_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee', 'get_enable_fee' );
```
You forgot to register the second fee ajax action.
It should be like that.
add_action( 'wp_ajax_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_enable_fee_2', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee_2', 'get_enable_fee' );
I am doing an Ajax call and return the value. The post id is coming. But when i tried with this code, It is return blank
function visa_status() {
$postid = $_POST['appid'];
// args
$args = array(
'numberposts' => 1,
'post_type' => 'cpt_15',
'meta_key' => 'application_number',
'meta_value' => $postid
);
$metaarry = array();
// query
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$posti = get_the_ID();
endwhile;
//echo $posti;
echo get_post_meta( $posti, 'given_name');
exit();
}
In the above code, $posti is coming. But get_post_meta() is not working.
This is my JS part
onStepChanging: function (event, currentIndex, newIndex) {
if ( newIndex === 1 ) {
jQuery('.wizard > .steps ul').addClass('step-2');
appId = jQuery('#appid').val();
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: my_ajax_object.ajax_url,
data: {
'action': 'visa_status',
'appid': appId,
},
success: function (msg) {
console.log(msg);
}
});
} else {
jQuery('.wizard > .steps ul').removeClass('step-2');
}
if ( newIndex === 2 ) {
jQuery('.wizard > .steps ul').addClass('step-3');
} else {
jQuery('.wizard > .steps ul').removeClass('step-3');
}
return true;
},
Is there any mistake i have done. Please help me in this.
Try this
$given_name = get_post_meta( $posti, 'given_name', true );
echo $given_name;
OR Try this
echo get_post_meta( $posti, 'given_name', true );
Check here what get_post_meta function returns based on 3rd parameter.
I'm trying to use the wordpress form to show the results with ajax and append into a div, here's my code:
jQuery( document ).ready(function ( $ ) {
$( "#searchform" ).on( "submit", function ( ev ) {
ev.preventDefault();
$.post(
"<?php echo admin_url( 'admin-ajax.php' ) ?>",
{
action: "wpa56343_search",
search: $( "#s" ).val()
},
function ( response ) {
$( ".search-content" ).html( response );
}
);
});
});
And this is in my functions.php
function wpa56343_search() {
if ( ! isset( $_POST['search'] ) )
exit;
query_posts(
array(
'posts_per_page' => 5,
'no_found_rows' => true,
'post_type' => get_post_types( array( 'public' => true ) ),
's' => wp_unslash( ( string ) $_POST['search'] ),
)
);
}
add_action( 'wp_ajax_nopriv_wpa56343_search', 'wpa56343_search', 100 );
add_action( 'wp_ajax_wpa56343_search', 'wpa56343_search', 100 );
What am I missing? thank you.
Attempting to integrate this nice tutorial from #dingo_d into a Woocommerce archive-product.php template. Here's what I've got so far:
archive-product.php
Added $cat_id under get_header
get_header( 'shop' );
$cat_id = get_query_var('cat');
Wrapped the loop with div
<main id="main" class="site-main ajax_posts" role="main">
<?php woocommerce_product_loop_start(); ?>
...
<?php woocommerce_product_loop_end(); ?>
</main><!-- /#main -->
pagination.php
the template file being overridden by my theme with the woocommerce pagination commented out
<div id="more_posts" data-category="<?php echo esc_attr($cat_id); ?>"><?php esc_html_e('Load More', 'siiimple') ?></div>
<!--<nav class="woocommerce-pagination">
<?php
echo paginate_links( apply_filters( 'woocommerce_pagination_args', array(
'base' => esc_url_raw( str_replace( 999999999, '%#%', remove_query_arg( 'add-to-cart', get_pagenum_link( 999999999, false ) ) ) ),
'format' => '',
'add_args' => false,
'current' => max( 1, get_query_var( 'paged' ) ),
'total' => $wp_query->max_num_pages,
'prev_text' => '←',
'next_text' => '→',
'type' => 'list',
'end_size' => 3,
'mid_size' => 3
) ) );
?>
</nav>-->
functions.js
( function( $ ) {
//LOAD MORE
var $content = $('.ajax_posts');
var $loader = $('#more_posts');
var cat = $loader.data('category');
var ppp = 3;
var offset = $('#main').find('.post').length;
$loader.on( 'click', load_ajax_posts );
function load_ajax_posts() {
if (!($loader.hasClass('post_loading_loader') ||
$loader.hasClass('post_no_more_posts'))) {
$.ajax({
type: 'POST',
dataType: 'html',
url: screenReaderText.ajaxurl,
data: {
'cat': cat,
'ppp': ppp,
'offset': offset,
'action': 'mytheme_more_post_ajax'
},
beforeSend : function () {
$loader.addClass('post_loading_loader').html('');
},
success: function (data) {
var $data = $(data);
if ($data.length) {
var $newElements = $data.css({ opacity: 0 });
$content.append($newElements);
$loader.removeClass('post_loading_loader');
$newElements.animate({ opacity: 1 });
$loader.removeClass('post_loading_loader').html(screenReaderText.loadmore);
} else {
$loader.removeClass('post_loading_loader').addClass('post_no_more_posts').html(screenReaderText.noposts);
}
},
error : function (jqXHR, textStatus, errorThrown) {
$loader.html($.parseJSON(jqXHR.responseText) + ' :: ' + textStatus + ' :: ' + errorThrown);
console.log(jqXHR);
},
});
}
offset += ppp;
return false;
}
//LOAD MORE
} )( jQuery );
functions.php
Placed at bottom of functions.php
// LOAD MORE
$ajaxurl = '';
if( in_array('sitepress-multilingual-cms/sitepress.php', get_option('active_plugins')) ){
$ajaxurl .= admin_url( 'admin-ajax.php?lang=' . ICL_LANGUAGE_CODE );
} else{
$ajaxurl .= admin_url( 'admin-ajax.php');
}
// END LOAD MORE
wp_localize_script( 'twentysixteen-script', 'screenReaderText', array(
'expand' => __( 'expand child menu', 'siiimple' ),
'collapse' => __( 'collapse child menu', 'siiimple' ),
//LOAD MORE
'ajaxurl' => $ajaxurl,
'noposts' => esc_html__('No older posts found', 'siiimple'),
'loadmore' => esc_html__('Load more', 'siiimple')
// END LOAD MORE
) );
//LOAD MORE
add_action('wp_ajax_nopriv_mytheme_more_post_ajax', 'mytheme_more_post_ajax');
add_action('wp_ajax_mytheme_more_post_ajax', 'mytheme_more_post_ajax');
if (!function_exists('mytheme_more_post_ajax')) {
function mytheme_more_post_ajax(){
$ppp = (isset($_POST['ppp'])) ? $_POST['ppp'] : 3;
$cat = (isset($_POST['cat'])) ? $_POST['cat'] : 0;
$offset = (isset($_POST['offset'])) ? $_POST['offset'] : 0;
$args = array(
'post_type' => 'product',
'posts_per_page' => $ppp,
'cat' => $cat,
'offset' => $offset,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) :
while ($loop -> have_posts()) :
$loop -> the_post();
$category_out = array();
$categories = get_the_category();
foreach ($categories as $category_one) {
$category_out[] ='' .$category_one->name.'';
}
$category_out = implode(', ', $category_out);
$cat_out = (!empty($categories)) ? '<span class="cat-links"><span class="screen-reader-text">'.esc_html__('Categories', 'twentysixteen').'</span>'.$category_out.'</span>' : '';
$out .= '<article id="post-'. get_the_ID().'" class="'. implode(' ', get_post_class()) .'">
<header class="entry-header">';
$out .= '<h2 class="entry-title">'.get_the_title().'</h2>';
$out .= '</header>'.
'</article>';
endwhile;
endif;
wp_reset_postdata();
wp_die($out);
}
}
//END LOAD MORE
That's it. Don't think I'm missing anything...Thanks!