Wordpress search function with ajax - ajax

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.

Related

How to enable more than one fee with ajax in Woocommerce checkout?

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' );

Add a fee for specific user roles when "Ship to a different address?" has been checked on WooCommerce checkout

I have a wholesale site with different user roles & want to allow employees to start ordering online from here also.
I want to only add a $5 fee if the user roles 'team' and 'team2' select ship to a different address (they get free shipping if sent to their billing address).
No other user role should see the fee if selecting the ship to a different address.
This is the closest solution I've found to make this happen but need help configuring this code to apply to only those two user roles and no one else.
// send as gift for Team & Team2 role add $5 fee
add_filter( 'woocommerce_form_field' , 'remove_order_comments_optional_fields_label', 10, 4 );
function remove_order_comments_optional_fields_label( $field, $key, $args, $value ) {
// Only on checkout page for Order notes field
if( 'ship_to_different_address' === $key && is_checkout() ) {
$optional = ' <span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
$field = str_replace( $optional, '', $field );
}
return $field;
}
// Ajax / jQuery script
add_action( 'wp_footer', 'ship_to_different_address_script' );
function ship_to_different_address_script() {
// On checkoutpage
if( ( is_checkout() && ! is_wc_endpoint_url() ) ) :
?>
<script type="text/javascript">
jQuery( function($){
if (typeof woocommerce_params === 'undefined')
return false;
console.log('defined');
$('input[name=ship_to_different_address]').click( function(){
var fee = $(this).prop('checked') === true ? '1' : '';
$.ajax({
type: 'POST',
url: woocommerce_params.ajax_url,
data: {
'action': 'ship_to_different_address',
'ship_to_different_address': fee,
},
success: function (result) {
$('body').trigger('update_checkout');
console.log(result);
},
});
});
});
</script>
<?php
endif;
}
// Get the ajax request and set value to WC session
add_action( 'wp_ajax_ship_to_different_address', 'get_ajax_ship_to_different_address' );
add_action( 'wp_ajax_nopriv_ship_to_different_address', 'get_ajax_ship_to_different_address' );
function get_ajax_ship_to_different_address() {
if ( isset($_POST['ship_to_different_address']) ) {
WC()->session->set('ship_to_different_address', ($_POST['ship_to_different_address'] ? '1' : '0') );
echo WC()->session->get('ship_to_different_address');
}
die();
}
// Add / Remove a custom fee
add_action( 'woocommerce_cart_calculate_fees', 'add_remove_ship_to_different_address', 10, 1 );
function add_remove_ship_to_different_address( $cart )
{
// Only on checkout
if ((is_admin() && !defined('DOING_AJAX')) || is_cart())
return;
$fee_amount = 5.00;
if (WC()->session->get('ship_to_different_address'))
$cart->add_fee(__('Shipping fee', 'woocommerce'), $fee_amount);
}
Your code contains some mistakes, missing pieces, and unnecessary steps.
This answer shows (without any user restrictions) how to add a fee when "Ship to a different address?" has been checked:
// The jQuery Ajax request
function action_wp_footer() {
// Only checkout page
if ( is_checkout() && ! is_wc_endpoint_url() ) :
// Remove "ship_different" custom WC session on load
if ( WC()->session->get( 'ship_different' ) ) {
WC()->session->__unset( 'ship_different' );
}
// jQuery Ajax code below
?>
<script type="text/javascript">
jQuery( function($) {
if ( typeof wc_checkout_params === 'undefined' )
return false;
var a = '#ship-to-different-address-checkbox', b = '';
// Ajax function
function triggerSTDA( value ) {
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'ship_different_address',
'ship_different': value,
},
success: function (result) {
$( 'body' ).trigger( 'update_checkout' );
// console.log( result ); // For testing (to be removed)
}
});
}
$( a ).on( 'change', function() {
b = $( this ).prop('checked') === true ? 'yes' : 'no';
triggerSTDA( b );
});
});
</script>
<?php
endif;
}
add_action( 'wp_footer', 'action_wp_footer' );
// The Wordpress Ajax PHP receiver
function get_ajax_ship_different_address() {
if ( isset( $_POST['ship_different'] ) ) {
WC()->session->set( 'ship_different', esc_attr( $_POST['ship_different'] ) );
echo $_POST['ship_different'];
}
die();
}
add_action( 'wp_ajax_ship_different_address', 'get_ajax_ship_different_address' );
add_action( 'wp_ajax_nopriv_ship_different_address', 'get_ajax_ship_different_address' );
// Add / remove a custom fee
function action_woocommerce_cart_calculate_fees( $cart ) {
// Only on checkout
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || is_cart() )
return;
$fee_amount = 5;
if ( WC()->session->get( 'ship_different' ) == 'yes' ) {
$cart->add_fee( __( 'Shipping fee', 'woocommerce'), $fee_amount );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
However, your question was to only apply this based on certain user roles:
So you get:
// The jQuery Ajax request
function action_wp_footer() {
// Only for logged in users
if ( ! is_user_logged_in() )
return;
// Only checkout page
if ( is_checkout() && ! is_wc_endpoint_url() ) :
// Remove "ship_different" custom WC session on load
if ( WC()->session->get( 'ship_different' ) ) {
WC()->session->__unset( 'ship_different' );
}
// jQuery Ajax code below
?>
<script type="text/javascript">
jQuery( function($) {
if ( typeof wc_checkout_params === 'undefined' )
return false;
var a = '#ship-to-different-address-checkbox', b = '';
// Ajax function
function triggerSTDA( value ) {
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'ship_different_address',
'ship_different': value,
},
success: function (result) {
$( 'body' ).trigger( 'update_checkout' );
// console.log( result ); // For testing (to be removed)
}
});
}
$( a ).on( 'change', function() {
b = $( this ).prop('checked') === true ? 'yes' : 'no';
triggerSTDA( b );
});
});
</script>
<?php
endif;
}
add_action( 'wp_footer', 'action_wp_footer' );
// The Wordpress Ajax PHP receiver
function get_ajax_ship_different_address() {
if ( isset( $_POST['ship_different'] ) ) {
WC()->session->set( 'ship_different', esc_attr( $_POST['ship_different'] ) );
echo $_POST['ship_different'];
}
die();
}
add_action( 'wp_ajax_ship_different_address', 'get_ajax_ship_different_address' );
add_action( 'wp_ajax_nopriv_ship_different_address', 'get_ajax_ship_different_address' );
// Add / remove a custom fee
function action_woocommerce_cart_calculate_fees( $cart ) {
// Only on checkout
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || is_cart() )
return;
// Only for logged in users
if ( ! is_user_logged_in() )
return;
// Get current WP_User Object
$user = wp_get_current_user();
// Roles to check, adapt to your specific needes
$roles_to_check = array( 'team', 'team2', 'administrator' );
// User roles
$roles = ( array ) $user->roles;
// Compare
$compare = array_diff( $roles, $roles_to_check );
// Result is empty
if ( empty ( $compare ) ) {
// Amount
$fee_amount = 5;
if ( WC()->session->get( 'ship_different' ) == 'yes' ) {
$cart->add_fee( __( 'Shipping fee', 'woocommerce'), $fee_amount );
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
Partly used in this answer
Show hide payment gateways based on checkout fields in Woocommerce
Checkbox field that add / remove a custom fee in WooCommerce
Check WooCommerce User Role and Payment Gateway and if they match - Apply fee

Get post meta in the Ajax not working in Wordpress

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.

How to load post in wordpress with ajax?

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!' );
}
);
}
);

Load More Posts Ajax Button in Woocommerce

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!

Resources