Pagination fails with CPT and dynamic tax_query - wordpress

I have a search form. Choose a taxonomy, and select one or more terms. I want to paginate the results.
Here is the code:
<?php
if(isset($_POST['tax_type'])) {
$tax_type=$_POST['tax_type'];
$terms = $_POST[$tax_type];
$term_list = implode("','", $terms);
$term_list1 = implode(", ", $terms);
$term_list = "'".$term_list."'";
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$giftfinder_args = array(
'post_type' => 'products',
'posts_per_page'=>"1",
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => $tax_type,
'field' => 'slug',
'terms' => explode(',',$term_list),
),
),
);
echo '<div class="results"><span class="eyebrow">search results</span>';
echo '<div class="cat_label">“' . $term_list1 . '”</div></div>';
// the query
$giftfinder_query = new WP_Query( $giftfinder_args );
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $giftfinder_query;
?>
<?php if ( $giftfinder_query->have_posts() ) : ?>
<!-- the loop -->
<?php while ( $giftfinder_query->have_posts() ) : $giftfinder_query->the_post();
$thumb = get_the_post_thumbnail(null, 'medium');
?>
<div class="prod"><?php if(empty($thumb)) {echo '<div style="width:265px;height:265px;background:#eee;"></div>';} else {the_post_thumbnail('medium');} ?><span class="truncate"><?php the_title(); ?></span></div>
<?php endwhile; ?>
<div style="clear:both;"></div>
<!-- end of the loop -->
<?php
the_posts_pagination( array(
'prev_text' => __( 'Previous page', 'twentyfifteen' ),
'next_text' => __( 'Next page', 'twentyfifteen' ),
'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentyfifteen' ) . ' </span>',
) );
?>
<?php wp_reset_postdata(); ?>
<?php else : get_template_part( 'content', 'none' ); endif; ?>
<?php } ?>
First page is fine, but no results appear on paginated pages.
As you can see, I'm trying to use the pagination fix that turns my query into $wp_query:
// the query
$the_query = new WP_Query( $args );
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $the_query;
But like I said, no results beyond first page.
I was going to try pre_get_posts but I can't figure out how to code it since every query has unique arguments based on the user's choice of taxonomy and searched terms.
I also tried 'add_args' to the paginate_links() function but could not figure out how to format the resulting get string.
BTW, right now, the query just returns one post to make it easy to check pagination.
Any suggestions appreciated!

Not sure if this is the only issue, but it looks like you have a typo.
You are setting $page:
$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
But looking for $paged:
'paged' => $paged,

Related

Cannot get pagination working in Wordpress Page template, already tried and failed a lot

I'm trying to get pagination working in a page template that I am making. I have already been through multiple threads on this website and I've also been searching through the Wordpress.org documentation (and the comments). Every time I reload my page, there is nothing where the pagination should be.
I've tried both get_posts() and WP_query(). WP_query is the one I believe is needed so that's the one I'll be giving you examples from.
Things I've already tried:
Using $paged = ( get_query_var( 'page' ) ) ? absint( get_query_var( 'page' ) ) : 1;
Also tried that last one with 'paged' instead of 'page'.
Using this in the arguments: 'posts_per_page' =>6, 'paged' => $paged,
And using this in the arguments 'posts_per_page=6&paged=' . $paged, 'paged' => $paged,
Tried resetting the query of my loops with wp_reset_query();
There are some other things I've tried too but the above are the ones I see recommended most often.
This is my full code in its current state (I've removed some things to help you read it).
I have tried to make the first loop with get_posts() instead and that didn't make a difference. I've also tried positioning commands like the wp_reset_query() in several different places.
The eventual goal is to have several of these loops on the same page, all except the first with pagination under them (I will be using ajax to allow users to cycle through the different content).
<?php /* Template Name: Home */ ?>
<div>
<?php
/*
First Loop - This one will stay the same on every page. Uses the same categories as the second loop.
*/
$categories = '
category-name1,category-name2
';
$query = new WP_Query( array( 'posts_per_page' =>4, 'category_name' => $categories ) );
?>
<div>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<div>
<?php get_template_part( 'entry-boxes-1' ); ?>
</div>
<?php endwhile; wp_reset_query(); endif; ?>
</div>
</div>
<div>
<?php
$paged = ( get_query_var( 'page' ) ) ? absint( get_query_var( 'page' ) ) : 1;
$query = new WP_Query( array( 'posts_per_page' =>6, 'paged' => $paged, 'category_name' => $categories, 'offset' => '4' ) );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
?>
<div>
<?php get_template_part( 'entry-boxes-1' ); ?>
</div>
<?php
endwhile; endif;
pagination_bar();
?>
</div>
Try this
<?php /* Template Name: Home */ ?>
<div>
<?php
/*
First Loop - This one will stay the same on every page. Uses the same categories as the second loop.
*/
$categories = array('category-name1' , 'category-name2');
$query = new WP_Query( array( 'posts_per_page' =>4, 'category_name' => $categories ) );
?>
<div>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<div>
<?php get_template_part( 'entry-boxes-1' ); ?>
</div>
<?php endwhile; wp_reset_query(); endif; ?>
</div>
</div>
<div>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query = new WP_Query( array( 'posts_per_page' =>6, 'paged' => $paged, 'category_name' => $categories, 'offset' => '4' ) );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
?>
<div>
<?php get_template_part( 'entry-boxes-1' ); ?>
</div>
<?php endwhile;
$total_pages = $query->max_num_pages;
if ($total_pages > 1){
$current_page = max(1, get_query_var('paged'));
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '/page/%#%',
'current' => $current_page,
'total' => $total_pages,
'prev_text' => false,
'next_text' => false,
));
}
wp_reset_postdata();
endif;
?>
</div>

How to show ACF in a WP_Query loop with 'post_type' => 'product'

Try to achieve this:
I made a ACF (custom field) in my WooCommerce Product and now I try to get this field shown in my template with this code:
<ul class="products">
<?php
$args = array(
'posts_per_page' => 20,
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_type',
'field' => 'name',
'terms' => 'grouped',
),
),
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
$linked_with_items = the_field('linked_with_items');
the_title('<strong>', '</strong>'); echo '<br />';
echo $linked_with_items;
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
</ul><!--/.products-->
But whatever I try also with get_field() the field does not show in my template.
Can someone help?
https://www.advancedcustomfields.com/
This is the final code fyi
<?php if( have_rows('catalogue') ): ?>
<?php
while( have_rows('catalogue') ): the_row(); // catalogue is the field
the_sub_field('linked_with_items'); ?>
<?php endwhile; ?>
<?php endif; ?>
You could try with this:
$linked_with_items = get_field('linked_with_items', get_the_ID());
If that doesn't work, just as a test, you could try to simply loop over posts with a foreach
foreach ( $loop->posts as $post ) {
$linked_with_items = get_field('linked_with_items', $post->ID);
}
If none of those work, please make sure that your product actually have that custom field, double check the ACF field settings (rule section), the field slug, and double check your product edit page to see if the fields shows there.

How to get all products with pagination in WordPress Woo commerce

Maybe this questions already asked but that not helpful for my question.
Am creating a API for my WordPress project. So i want to send API for to get all products with pagination.
I get products list using this code:
android/all_products.php
<?php
require_once('../wp-load.php');
$args = array(
'post_type' => 'product',
'posts_per_page' => 10
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo '<br />' . woocommerce_get_product_thumbnail().' '.get_the_title().'';
endwhile;
wp_reset_query();
?>
I got all products, but i want to show products with pagination.
Note: all the API's are written in inside android folder.
Thanks in advance.
below pagination code is to show next products you can also do it to show previous product by applying same method
if(isset( $_GET['page_num'] ) ) {
$page_number = $_GET['page_num'];
} else {
$page_number = 2;
}
$args = array (
'limit' => 3,
'page' => $page_number,
);
$products = wc_get_products( $args );
foreach( $products as $product ) {`enter code here`
//your data here
// e.g $product_name = $product->get_name();
}
Next
If you want to create API's then just use Woocommerce rest API's which are built in function given in wordpress please use below url it will give you list of products with lots of options:
{{your_url}}/wp-json/wc/v2/products
Go to wp-admin and go to Woocommerce -> settings -> API
-> Enable rest API
-> Go to Key/Apps and create Auth Keys both secret and Private (Copy that keys)
Then give this above url to add it for use in application with o_auth of secret key and private key.
Please see this link for all woocommerce API's : https://woocommerce.github.io/woocommerce-rest-api-docs/#retrieve-a-product
Finally i creating a code and send the date using API.
<?php
require_once('../wp-load.php');
$args = array(
'post_type' => 'product',
'posts_per_page' => -1
);
$brand_product_list = new WP_Query( $args);
$pagination_count = 1;
while($brand_product_list->have_posts()) : $brand_product_list->the_post();
$pagination_count++;
endwhile; wp_reset_query();
//echo'<pre>';print_r($pagination_count/12); exit;
wp_reset_query();
?>
<?php
$pagination = round($pagination_count/12);
for($i=1;$i<=$pagination;$i++)
{
$pagination_no[] = $i;
?>
<!-- <a class="product-category-view-all" href="?pagination=<?php echo $i; ?>"><?php echo $i; ?></a> -->
<?php } ?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : $_GET['pagination'];
$args = array(
'post_type' => 'product',
'paged' => $paged,
'posts_per_page' => 12,
);
$wp_query = new WP_Query($args);
while($wp_query->have_posts()) : $wp_query->the_post();
$product_data = wc_get_product( $post->ID );
if(!empty(get_the_post_thumbnail_url($product_data->get_id())))
{
$img = get_the_post_thumbnail_url($product_data->get_id());
}
else
{
$img = "";
}
$product_list[] = array(
'product_id' => $product_data->get_id(),
'product_name' => $product_data->get_title(),
'product_regular_price' => $product_data->get_regular_price(),
'product_sale_price' => $product_data->get_sale_price(),
'product_price' => $product_data->get_price(),
'img' => $img,
'rating' => $product_data->get_average_rating(),
'stock_quantity' => $product_data->get_stock_quantity(),
'stock' => $product_data->is_in_stock(),
);
endwhile; wp_reset_query();
$data[] = array(
'pagination' => $pagination_no,
'product_list' => $product_list
);
//echo json_encode($peoduct_list, $pagination)
echo json_encode($data)
?>

Get Image Size Advanced Custom Fields

I am trying to get an image URL with attachment size using an advanced custom field. The field is set to ID. I've used this approach to get other images by ID with no problem. Yet this one isn't pulling the rendered image. It's pulling the ID number and displaying it on the page. I'm stumped...
<?php
$the_query = new WP_Query( array(
'post_type' => 'listicles',
'tax_query' => array(
array (
'taxonomy' => 'visibility',
'field' => 'slug',
'terms' => 'listicles-resortsvisible',
),
),
) );
$listicleimage = the_field('listicle_featured_image', $post->ID);
$listicleimgsize = 'listicle-thumb';
$listicleimg_array = wp_get_attachment_image_src($listicleimage, $listicleimgsize);
$listicleimg_url = $listicleimg_array[0];
?>
<ul
class="row small-up-1 medium-up-2">
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li class="small-12 medium-6 column">
<img
src="<?php echo $listicleimg_url; ?>"
class="align-center" />
//THE REST OF MY CONTENT//
</li>
<?php endwhile;?>
<?php endif; ?>
</ul>
<?php wp_reset_query(); ?>
You only need to change
the_field('listicle_featured_image', $post->ID);
to
get_field('listicle_featured_image', $post->ID);
You should be using wp_get_attachment_image and not wp_get_attachment_image_src.
wp_get_attachment_image accepts ID's as an argument.
Source: https://developer.wordpress.org/reference/functions/wp_get_attachment_image/
Add this to functions.php
function img_by_id($id, $size, $url) {
$the_img = wp_get_attachment_image($id, $size);
if ($url != true) {
return $the_img;
}
else {
$img_src = get_attr($the_img, 'src');
return $img_src;
}
}
function get_attr($html, $attr) {
$pc = explode($attr.'="', $html);
$pc2 = explode('"', $pc[1]);
return $pc2[0];
}
Then
<?php
$the_query = new WP_Query( array(
'post_type' => 'listicles',
'tax_query' => array(
array (
'taxonomy' => 'visibility',
'field' => 'slug',
'terms' => 'listicles-resortsvisible',
),
),
) );
$listicleimage = the_field('listicle_featured_image', $post->ID);
$listicleimg_url = img_by_id( $listicleimage, 'listicle-thumb', true);
?>
if you need full image attribute with sizes $img = img_by_id( $listicleimage, 'listicle-thumb', false);
If you need specific attribute from html tag $attr = get_attr($html, $attr);
I have this on my blank WP theme template.

How to get number of results from query_posts?

I'm printing posts and I want to get number of results, how can I do that?
This is part of my code:
if (have_posts()) :
$args = array(
'showposts' => '5',
'paged' => $paged
);
$thePosts = query_posts($args);
...
Thank's for help
SOLVED:
if (have_posts()) :
$args = array(
'showposts' => '5',
'paged' => $paged
);
$thePosts = query_posts($args);
global $wp_query;
echo $wp_query->found_posts;
...
To display the number of results of a search, use:
Search Result for
<?php
/* Search Count */
$allsearch = &new WP_Query("s=$s&showposts=-1");
$key = wp_specialchars($s, 1);
$count = $allsearch->post_count; _e('');
_e('<span class="search-terms">');
echo $key; _e('</span>');
_e(' — ');
echo $count . ' ';
_e('articles');
wp_reset_query();
?>
This was taken from: WP Beginner.
The correct answer is
if (have_posts()) :
$args = array(
'showposts' => '5',
'paged' => $paged
);
$thePosts = query_posts($args);
echo $thePosts ->found_posts;
...
This will give you the results: Showing results 11-20 of 46, for instance.
$args = array(
'cat'=> $cat,
'posts_per_page' => 10,
'paged' => $paged,
's'=> $s
);
query_posts($args);
$startpost=1;
$startpost=10*($paged - 1)+1;
$endpost = (10*$paged < $wp_query->found_posts ? 10*$paged : $wp_query->found_posts);
?>
<h2 class="displayResult">Showing results <?php echo $startpost; ?> - <?php echo $endpost; ?> of <?php echo $wp_query->found_posts; ?></h2>
If this is not a search page, simply remove the line "'s'=> $s".
If you do need it, make sure you declare the variable as $_GET['s'] above.
Easy. To display number of results for this current page, use
// Showing Page X of Y
print filter_var( absint( $GLOBALS['wp_query']->post_count ), FILTER_SANITIZE_NUMBER_INT );
For the total amount of results, use
print filter_var( absint( $GLOBALS['wp_query']->found_posts ), FILTER_SANITIZE_NUMBER_INT );
display numbers of search results :
<?php global $wp_query;
echo $wp_query->post_count; ?>
query_posts( $args );
global $wp_query;
print_r($wp_query->max_num_pages);
It help me.

Resources