WP_Query on function not showing pagination - ajax

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.

Related

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.

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

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.

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

Filter posts by their post-type with dropdown menu

I want to filter posts by their post-type.
therefore I have created a dropdown menu where I can select one or multiple post-types.
My question now is: How do I get functionality for my dropdown, because I dont't know how to corespond with the database when the element is in the frontend.
This is my Dropdown-Menu
Using ajax you can filter post.
This is my code for filter post by category (filter post by multiple category selection)
ajax code
<script type="text/javascript">
$('.categorytag').click(function(){
var cokeValue = //you need to pass array of post category id
var data = {
action: 'get_partiblog',
foo: cokeValue
};
$.post('/wp-admin/admin-ajax.php',data,function(response){
$('#filteredblog').html(response);
});
})
</script>
php code
<?php
add_action('wp_ajax_get_partiblog','Getblogcatwise');
add_action('wp_ajax_nopriv_get_partiblog','Getblogcatwise');
function Getblogcatwise(){
$catids = $_POST['foo'];
foreach($catids as $catid){
$args = array(
'post_type'=> 'post',
'orderby' => 'ID',
'category_name' => $catid,
'post_status' => 'publish',
'order' => 'DESC',
'posts_per_page' =>-1 // this will retrive all the post that is published
);
$result = new WP_Query( $args );
if ( $result-> have_posts() ) :
while ( $result->have_posts() ) : $result->the_post();
$link = get_permalink();
echo '<a href="'.$link.'" target="_blank">';
echo '<div class="service-wrapper" style="border:1px solid #367bae;">';
/* if ( has_post_thumbnail() ){
echo '<div><img src="'.the_post_thumbnail("thumbnail").'" alt="Image Missing" rel="lightbox"></div>';
}else{
echo '<div><img src="https://uae.microless.com/cdn/no_image.jpg" alt="" rel="lightbox"></div>';
}*/
$title= get_the_title();
echo '<center><div style="color:#367bae;font-size:22px;font-weight:700;position: relative;margin-top: 25%;padding:5%;">'.$title.'</div></center>';
echo '<div class="service-wrapper-inner">';
//$title= get_the_title();
//echo '<h3>'.$title.'</h3>';
echo '<center><i style="font-size:18px;color:#fff;-webkit-transition: 1s;-moz-transition: 1s;-ms-transition: 1s;-o-transition: 1s; transition: 1s;" class="fa fa-bars"></i></center>';
$excerpt= the_excerpt();
echo '<div class="description"><p>'.$excerpt.'</p></div></div></div></a>';
endwhile;
endif; wp_reset_postdata();
}
}
?>

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