wp_ajax data_fetch not working if there's a CPT in the array - ajax

If I add the CPTs ('applicazione' and 'miscele') to 'post' and 'page' in the array they are not searched. If I leave just the CPTs it works. What am I doing wrong?
This is the code I am using.
// 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>
<?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(
'post_type' => array('post','page','applicazione','miscele'),
'post_status' => 'publish',
'posts_per_page' => -1,
's' => esc_attr( $_POST['keyword'] )
)
);
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h4><?php the_title();?></h4>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}

Solved.
The problem was the Polylang plugin. Adding the CPTs to the translation settings fixed the issue.

Related

Woocommerce mini-cart ajax apply coupon

I have been going in circles with this I have added an apply coupon field to mini-cart.php and am trying to get it to run without refreshing the whole page. Any suggestions would be amazing help.
functions:
function apply_coupon_code(){
$coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
WC()->cart->apply_coupon($coupon_code);
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );
Input:
<?php if (empty (WC()->cart->get_coupons())): ?>
<span id="coupon-form">
<?php if ( wc_coupons_enabled() ) { ?>
<form class="widget_shopping_cart_content" action="<?php echo $cart_url ?>" method="post">
<?php } else { ?>
<form id="apply-promo-code" class="widget_shopping_cart__coupon">
<?php } ?>
<label id="promo-code" for="coupon-code">Promo Code:</label>
<input id="minicart-coupon" class="input-text" type="text" value="" name="coupon_code"/>
<button type="submit" id="minicart-apply-button" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>"><?php esc_attr_e( 'Apply', 'woocommerce' ); ?></button>
<?php do_action( 'woocommerce_cart_coupon' ); ?>
<?php do_action( 'woocommerce_cart_actions' ); ?>
</form>
<?php endif; ?>
<?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
<span id="widget-shopping-cart-remove-coupon" class="mini_cart_coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
Promo Code: <?php echo esc_attr( sanitize_title( $code ) ); ?>
<?php $remove_url = $cart_url.'?remove_coupon='.$coupon->code; ?>
<?php wc_cart_totals_coupon_html( $coupon ); ?>
</span>
<?php endforeach; ?>
jQuery:
jQuery(document).on('click', 'button#minicart-apply-button', function() {
var coupon = jQuery( 'input#minicart-coupon' ).val();
var button = ( this );
var data = {
action: "apply_coupon_code",
coupon_code: "coupon"
};
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: wc_add_to_cart_params.ajax_url,
data: data,
success: function (response) {
console.log(response);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
});
You can get the new mini cart HTML inside your ajax callback on the server and then return that as a response to the jQuery ajax call then simply replace the whole mini cart HTML on the front-end with the updated HTML.
function apply_coupon_code(){
$coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
WC()->cart->apply_coupon($coupon_code);
ob_start();
woocommerce_mini_cart();
$cart_html = ob_get_clean();
return $cart_html;
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );
The output buffer is used here as woocommerce_mini_cart uses wc_get_template which just echoes out the content. The output buffer will allow you to capture this as a string.
Now you need to tell jQuery that you're expecting HTML back from the server...
jQuery(document).on('click', 'button#minicart-apply-button', function() {
var coupon = jQuery( 'input#minicart-coupon' ).val();
var button = ( this );
var data = {
action: "apply_coupon_code",
coupon_code: "coupon"
};
jQuery.ajax({
type: 'POST',
dataType: 'html',
url: wc_add_to_cart_params.ajax_url,
data: data,
success: function (response) {
console.log(response);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
});
Now response will have the new HTML for the mini-cart, so you can replace it using jQuery's html() function...
success: function (response) {
console.log(response);
jQuery('.mini-cart-wrapper').html(response);
},

AJAX Search returns "You do not have sufficient permissions to access this page" on non-admin user

I have this demo website that I'm making:
https://theme.artware.gr/
The problem I am facing is on the search functionality. You can click on the right/top side search to see the issue. When I am logged-in as admin, the search works fine, but when I view the page as a guest I get the error: "You do not have sufficient permissions to access this page".
This is my code so far:
// AJAX Search (no WooCommerce)
if ( !class_exists( 'WooCommerce' ) ) {
function simple_search_scripts(){
wp_enqueue_script( 'simple_search', get_stylesheet_directory_uri() . '/js/search.js', array(), '1.0.0', true);
wp_localize_script('simple_search', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ), 'nonce' => wp_create_nonce('ajax-nonce') ));
}
// Create shortcode
function simple_search(){
simple_search_scripts(); ?>
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="<?php _e('Αναζήτηση...'); ?>" />
<div id="datafetch"></div>
<?php
}
add_shortcode('simple_search', 'simple_search');
// Fetch data
function simple_search_callback(){
$the_query = new WP_Query( array( 'posts_per_page' => 10, 's' => esc_attr( $_GET['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) : while( $the_query->have_posts() ) : $the_query->the_post();
$myquery = esc_attr( $_GET['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) { ?>
<div class="result-sin">
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' ); ?>
<div class="result-sin-img">
<?php if ($image) { ?>
<img src="<?php echo $image[0]; ?>" width="<?php echo $image[1]; ?>" height="<?php echo $image[2]; ?>" />
<?php } ?>
</div>
<div class="result-sin-tit"><?php the_title();?></div>
<div class="result-sin-txt"><?php the_excerpt();?></div>
</div>
<?php }
endwhile;
wp_reset_postdata();
endif;
die();
}
add_action('wp_ajax_simple_search', 'simple_search_callback' );
add_action('wp_ajax_nopriv_simple_search', 'simple_search_callback' );
}
And the search.js:
function fetch(){
jQuery.ajax({
async: true,
url: myAjax.ajaxurl,
type: 'GET',
data: {
action: 'simple_search',
keyword: jQuery('#keyword').val(),
nonce: myAjax.nonce
},
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
And on the header, I simply call a shortcode [simple_search] . Everything post I read on SO said that the wp_ajax_nopriv_ACTION was missing. But I already have that.
UPDATE
I tried using method GET, that didn't work. I also used: wp_localize_script('simple_search', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ), 'nonce' => wp_create_nonce('ajax-nonce') )); to better enqueue the admin-ajax.php, that didn't work either.
Somewhere In my theme I had require_once('file.php') that had the line below:
if ( !current_user_can( 'manage_options' ) ) { wp_die( __( 'You do not have sufficient permissions to access this page.' ) ); }
When I removed this, the problem was fixed.

Search live Ajax Woocommerce

It is necessary to reach the search entries instantly, but why can I cause such an error?
This error : POST https://localhost/theme/wp-admin/admin-ajax.php 500 (Internal Server Error)
Following my code:
HTML
<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>
<div id="datafetch">Search results will appear here</div>
functions.php
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 );
console.log(data);
}
});
}
</script>
<?php }
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'operator' => 'NOT'
);
$query = new WC_Product_Query(
array(
'tax_query' => $tax_query,
'posts_per_page' => -1,
's' => esc_attr( $_POST['keyword'] ),
'post_type' => 'post'
)
);
$products = $query->get_products();
if($products) {
foreach( $products as $product) {
echo '
'. $product->get_name() .' ';
}
}
wp_reset_postdata();
die();
}
i am getting an error like this
debug.log
Stack trace:
#0 C:\xampp\htdocs\theme\wp-includes\class-wp-hook.php(303): data_fetch('')
#1 C:\xampp\htdocs\theme\wp-includes\class-wp-hook.php(327): WP_Hook->apply_filters('', Array)
#2 C:\xampp\htdocs\theme\wp-includes\plugin.php(470): WP_Hook->do_action(Array)
#3 C:\xampp\htdocs\theme\wp-admin\admin-ajax.php(187): do_action('wp_ajax_data_fe...')
#4 {main}
Thank you advance

WP_Query on function not showing pagination

I have this code and its working fine, the only problem is that its not showing pagination. This code is on my functions.php file.
add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
global $post;
$cat_id = $_POST[ 'cat' ];
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array (
'cat' => $cat_id,
'posts_per_page' => 6,
'order' => 'DESC',
'paged' => $paged
);
$cat_query = new WP_Query($args);
if($cat_query->have_posts()) :
while($cat_query->have_posts()) : $cat_query->the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
wp_reset_query();
?>
<div class="page-nation">
<ul class="pagination pagination-large">
<?php
$pagination = get_the_posts_pagination(array(
'mid_size' => 2,
'prev_text' =>esc_html__('Previous', 'travel-tour'),
'next_text' => esc_html__('Next', 'travel-tour'),
'screen_reader_text' => ' ',
) );
echo $pagination;
?>
</ul>
</div>
<?php
endif;
die();
}
and this is my jquery ajax script
<script>
jQuery(document).ready(function () {
jQuery('.js-category-button').on('click', function(e){
e.preventDefault();
jQuery('.preloadswitch').addClass('addpreloader');
var catID = jQuery(this).data('slug');
var catName = jQuery(this).attr('href');
var ajaxurl = '<?php echo esc_js( admin_url( 'admin-ajax.php' ) ) ?>';
jQuery.ajax({
type: 'POST',
url: ajaxurl,
crossDomain : true,
dataType: 'html',
data: {"action": "load-filter", cat: catID },
beforeSend: function () {
jQuery(".the-categories").html('<div></div>').fadeIn('slow');
jQuery(".page-nation").hide();
//window.location.hash = "#"+jQuery("#comehere").attr("id");
jQuery('html,body').animate({scrollTop:jQuery('#comehere').offset().top}, 1000);
window.history.pushState('obj', 'newtitle', catName);
},
success: function(response) {
jQuery(".the-categories").append(response);
jQuery('.preloadswitch').removeClass('addpreloader');
return false;
}
});
})
});
</script>
I don't what to do here anymore, I have been searching on the web for possible working function but with no luck.
I just need to show the pagination
Comment out or remove the wp_reset_query();, or move it to after the pagination; and use paginate_links() instead of get_the_posts_pagination().
Here's the altered 'if-else' block in your prefix_load_cat_posts() function:
if($cat_query->have_posts()) :
while($cat_query->have_posts()) : $cat_query->the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
//wp_reset_query();
?>
<div class="page-nation">
<ul class="pagination pagination-large">
<?php
$pagination = paginate_links(array(
'mid_size' => 2,
'prev_text' =>esc_html__('Previous', 'travel-tour'),
'next_text' => esc_html__('Next', 'travel-tour'),
'current' => $paged,
'total' => $cat_query->max_num_pages,
'type' => 'array',
'base' => home_url( '/%_%' ),
) );
echo '<li>' . implode( '</li><li>', $pagination ) . '</li>';
?>
</ul>
</div>
<?php
endif;
[EDIT] Try setting the base parameter.

How to paging when load ajax with wp_query?

I have an AJAX function that runs a PHP WP_Query function, and I'm not sure how these results would be outputted dynamically with pagination. The code in function.php
function feature_procject_list() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ): ?>
<?php
$post_type = $_REQUEST['post_type'];
$id_cat = $_REQUEST['id_cat'];
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$arr_2 = array(
'posts_per_page'=> 4,
'cat' => $id_cat,
'paged' => $paged,
);
$wp_query = new WP_Query( $arr_2 );
?>
<?php if($wp_query->have_posts()): ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<div class="single_project">
<a class='img_thumb' href="<?php echo get_permalink();?>"><?php the_post_thumbnail('medium'); ?></a>
<h4><?php the_title(); ?></h4>
<p class="date"><?php the_date('j F \a\t G:i'); ?></p>
<?php the_excerpt(); ?>
</div>
<?php endwhile;
//wp_reset_postdata();
?>
<div id="paging_wrap">
<?php my_pagination(); ?>
<?php //paginate(); ?>
</div><!-- #paging_wrap -->
<?php else: ?>
<h4><?php _e( 'Sorry, no posts matched your criteria.' ); ?></h4>
<?php endif; ?>
<?php endif;die();
}
add_action( 'wp_ajax_feature_procject_list', 'feature_procject_list' );
add_action( 'wp_ajax_nopriv_feature_procject_list', 'feature_procject_list' );
function my_pagination() {
global $wp_query;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages
) );
}
And get it on the page template:
function get_list_feature_project(id_category) {
$.ajax({
url: ajaxurl,
data: {
'action':'feature_procject_list',
'id_cat' : id_category
},
beforeSend : function(){
$('#loading').show();
},
success:function(data) {
// This outputs the result of the ajax request
$('#loading').hide();
$('.list_post').html(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
The post still show but paging not working.

Resources