on second page slider is not showing in pagination - wordpress

I have created a short-code for fetching posts using custom post type with pagination, and it works fine but when I go to second page using pagination slider is not showing.Here is the code that I have used:
<?php function artistCategoryFunction($args){
global $wpdb;
global $posts;
$term = get_term($args['categoryid'],'artists_category');
$name = $term->slug;
$catId = explode(',',$args['categoryid']);
$perPage = $args['post_per_page'];
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$posts_array = new WP_Query(
$data = array(
'posts_per_page' => $perPage,
'post_type' => 'artists',
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'artists_category',
'field' => 'term_id',
'terms' => $catId,
'operator'=> 'IN'
)
)
)
);
//echo '<pre>';print_r($posts_array->posts);
$grid = '<div class="category"><ul>';
if ( $posts_array->have_posts() ) : while ( $posts_array->have_posts() ) : $posts_array->the_post();
$post_id = $values->ID;
$title = get_the_title();
$thisposts = get_post($post_id);
$thisposts = $thisposts->post_name;
$mobile_img = get_field('featured_mobile_image');
$content = get_field('description_(short)');
$feature_img = wp_get_attachment_url( get_post_thumbnail_id());
if($mobile_img == '')
{
$mobile_img = $feature_img;
}
else{
$mobile_img;
}
$grid .= '<li><div class="cate-box">
<div class="cate-pic"><img src="'.$mobile_img.'" alt=" "></div>
<div class="cate-ctn">
<h4>'.$title.'</h4><p>'.$content.
'</p><span class="read-box">read more</span>
</div></div></li>';
endwhile;endif;wp_reset_query();
$total_pages = $posts_array->max_num_pages;
if ($total_pages > 1){
$current_page = max(1, get_query_var('paged'));
$grid .= '<div class="page_nav">';
$grid .= paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%',
'current' => $current_page,
'total' => $total_pages,
'prev_text' => 'Prev',
'next_text' => 'Next'
));
$grid .= '</div>';
}
$grid .= '</ul></div>';
return $grid;
}
add_shortcode('artistGrid','artistCategoryFunction');?>

I had a simular issue in one of my sites, and in my case the problam was in $paged variable and more precicely in the way its value was taken.
You can try this code, it works for me:
$paged = get_query_var( 'paged' ) ?: ( get_query_var( 'page' ) ?: 1 );

Related

Wordpress pagination does not show

For a new WordPress template I coded a loop that works fine. But there is no pagination. Does anyone see, why there is no pagination shown?
Thanks!
My loop:
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'post_type' => 'post',
'numberposts' => -1,
'posts_per_page' => 9,
'paged' => $paged,
'cat' => '4'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
......
<?php
}
} else { echo 'no posts found'; }
wp_reset_postdata();
?>
And on the bottom of the page:
<?php the_posts_pagination( array( 'mid_size' => 2 ) ); ?>
Please try this.
if ( ! function_exists( 'pagination' ) ) :
function pagination( $paged = '', $max_page = '' ){
global $wp_query
$big = 999999999; // need an unlikely integer
if( ! $paged )
$paged = get_query_var('paged');
if( ! $max_page )
$max_page = $wp_query->max_num_pages;
echo paginate_links( array(
'base' => str_replace($big, '%#%', esc_url(get_pagenum_link( $big ))),
'format' => '?paged=%#%',
'current' => max( 1, $paged ),
'total' => $max_page,
'mid_size' => 2,
'prev_text' => __('«'),
'next_text' => __('»'),
'type' => 'list'
) );
}
endif;
And the loop template will be like -
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1; $args = array(
''post_type' => 'post',
'posts_per_page' => 9,
'paged' => $paged,
'cat' => '4'
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
get_template_part( 'content', get_post_format() );
endwhile;
pagination($paged, $loop->max_num_pages);// Pagination Function
endif;
wp_reset_postdata();

Custom Post types Pagination shows up but 404s

I can't get pagination to work with custom post types.
It's showing up correctly, when I click it goes to /page/2 and /page/3 etc, and all those give a 404 Page not found error.
index.php
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => array('name1', 'name2', 'name3', 'post'),
'posts_per_page' => 4,
'post_status' => 'publish',
'paged' => $paged
);
$query = new WP_Query( $args );
?>
<?php echo $paged; ?>
<?php if ($query->have_posts()) : ?>
<?php while ($query->have_posts()) : $query->the_post(); ?>
// do stuff here
<?php the_excerpt(); ?>
<?php endwhile; ?>
// get pagination
<?php mypagination( $query ); ?>
<?php endif; ?>
<?php wp_reset_query(); ?>
functions.php
the built in the_posts_pagination() doesn't output anything.
function mypagination($query){ ?>
<ul class="pagination">
<?php
$pages = paginate_links( array(
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'total' => $query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => true,
'type' => 'array',
'end_size' => 2,
'mid_size' => 1,
'prev_next' => true,
'prev_text' => '<span class ="fa fa-caret-left" aria-hidden="true"></span><span class="prev-text">Prev</span>',
'next_text' => '<span class="next-text">Next</span> <span class ="fa fa-caret-right" aria-hidden="true"></span>',
'add_args' => false,
'add_fragment' => '',
) );
if (is_array($pages)):
foreach ($pages as $p): ?>
<li class="pagination-item js-ajax-link-wrap">
<?php echo $p; ?>
</li>
<?php endforeach;
endif; ?>
</ul>
<?php
}
If I create a custom API endpoint with the same query/arguments, pagination IS working.
/**
* Custom JSON API endpoint.
* Endpoint URL http://localhost/websitename/wp-json/frontpage/v1
*/
function api_frontpage_posts($data) {
$output = array();
// Get post slug.
$post = get_post($data['parent_id']);
$slug = $post->post_name;
// e.g. 1, 2, 3,...
$paged = $data['page_number'] ? $data['page_number'] : 1;
$query_args = array(
'post_type' => array('name1', 'name2', 'name3', 'post'),
'post_status' => array('publish'),
'posts_per_page' => 4,
'paged' => $paged,
);
// Create a new instance of WP_Query
$the_query = new WP_Query($query_args);
if (!$the_query->have_posts()) {
return null;
}
while ($the_query->have_posts()) {
$the_query->the_post();
$post_id = get_the_ID();
$post_title = get_the_title();
$post_content = get_the_content();
$post_excerpt = get_the_excerpt();
$post_date = get_the_date('l, j F Y');
// Get the slug.
$post = get_post($post_id);
$post_slug = $post->post_name;
// Get image alt.
$alt = get_post_meta(get_post_thumbnail_id(), '_wp_attachment_image_alt', true);
$desc = get_post_meta(get_post_thumbnail_id(), '_wp_attachment_image_caption', true);
// Get image description.
$description = null;
$thumbnail = get_posts(array('p' => get_post_thumbnail_id(), 'post_type' => 'attachment'));
if ($thumbnail && isset($thumbnail[0])) {
$description = $thumbnail[0]->post_content;
}
// Image data.
$post_image = array(
'id' => get_post_thumbnail_id() ,
'url' => get_the_post_thumbnail_url(),
'caption' => get_the_post_thumbnail_caption(),
'alt' => $alt,
'description' => $description,
);
// Category data.
$categories = get_the_category($post_id);
$post_categories = array();
foreach ($categories as $key => $category) {
$post_categories[] = array(
'name' => $category->name,
'slug' => $category->slug,
'url' => get_category_link($category->cat_ID),
);
}
// Push the post data into the array.
$output[] = array(
'id' => "post" . $post_id, // cannot use numbers, or hyphens between words for Zurb data toggle attribute
'slug' => $post_slug,
'title' => $post_title,
'url' => get_permalink($post_id),
'date' => $post_date,
'content' => $post_content,
'excerpt' => $post_excerpt,
'image' => $post_image,
'categories' => $post_categories
);
}
$result = array(
"next" => (int)$paged === (int)$the_query->max_num_pages ? null : site_url() . '/' . $slug . '/page/' . ($paged + 1) . '/',
"prev" => (int) $paged === 1 ? null : site_url() . '/' . $slug . '/page/' . ($paged - 1) . '/',
// Split the array every 4 items.
"chunks" => array_chunk($output, 4)
);
// Reset the post to the original after loop. otherwise the current page
// becomes the last item from the while loop.
wp_reset_query();
// Return json.
return $result;
}
add_action('rest_api_init', function () {
register_rest_route('frontpage/v1', '/page/(?P<page_number>\d+)', array(
'methods' => 'GET',
'callback' => 'api_frontpage_posts',
));
});
(hooray Reddit)
Someone pointed me to the fix.
Add this to functions.php too, via https://wordpress.stackexchange.com/questions/22528/custom-post-type-pagination-404-fix
add_action( 'parse_query','changept' );
function changept() {
if( is_category() && !is_admin() )
set_query_var( 'post_type', array( 'post', 'your_custom_type' ) );
return;
}

How to retrieve posts(books) based on category(taxonomy) in wordpress?

I am trying to display posts of specific category(taxonomy) that is 'Book1'.
I tried to display it with the following code.
$args = array(
'post_type' => 'book',
'posts_per_page' => 6,
'tax_query' => array(
array(
'taxonomy' => 'Book1',
'field' => 'id',
'terms' => 1
)
)
);
echo '<br>';
$postss = get_posts( $args );
if ( ! empty( $postss ) && is_array( $postss ) ) {
// Run a loop and print them all
$i=1;
foreach ( $postss as $termm ) {
echo ' '.$i.' '.$termm->post_title. '<br>';
$i++;
}
}
?>
In output no any item is displayed.
$custom_terms = get_terms('Book1');
foreach($custom_terms as $custom_term) {
wp_reset_query();
$args = array(
'post_type' => 'book',
'posts_per_page' => 6,
'tax_query' => array(
array(
'taxonomy' => 'Book1',
'field' => 'slug',
'terms' => $custom_term->slug,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
echo '<h2>'.$custom_term->name.'</h2>';
while($loop->have_posts()) : $loop->the_post();
echo ''.get_the_title().'<br>';
endwhile;
}
}
try this code
$args = array(
'post_type' => 'book',
'posts_per_page' => 6,
'tax_query' => array(
array(
'taxonomy' => 'Book1',
'field' => ''term_id', // here you are worng name too
'terms' => 1
)
)
);
echo '<br>';
$postss = get_posts( $args );
if ( ! empty( $postss ) && is_array( $postss ) ) {
// Run a loop and print them all
$i=1;
foreach ( $postss as $termm ) {
echo ' '.$i.' '.$termm->post_title. '<br>';
$i++;
}
}
?>
// best solution
<?php
$query = new WP_Query( array(
'post_type' => 'book', // name of post type.
'tax_query' => array(
array(
'taxonomy' => 'Book1', // taxonomy name
'field' => 'term_id', // term_id, slug or name
'terms' => 1, // term id, term slug or term name
)
)
) );
while ( $query->have_posts() ) : $query->the_post();
// do stuff here....
endwhile;
/**
* reset the orignal query
* we should use this to reset wp_query
*/
wp_reset_query();
?>
I did it by doing like this. Thanks all.
$args = array(
'post_type' => 'book',
'cat' => '35'
);
echo '<br>';
$postss = query_posts($args);
if ( ! empty( $postss ) && is_array( $postss ) ) {
// Run a loop and print them all
?><?php $i=1;
foreach ( $postss as $termm ) { ?>
<?php echo ' '.$i.' '.$termm->post_title. '<br>';$i++;?>
<?php
}
}

I can't get pagination to work in WP query

This is what my current wordpress post query looks like:
<?php
$new_loop = new WP_Query( array(
'post_type' => 'news',
'posts_per_page' => 5
) );
?>
I want to add the following pagination to it:
<?php the_posts_pagination( array(
'mid_size' => 2,
'prev_text' => __( 'Prev'),
'next_text' => __( 'Next'),
) ); ?>
I googled for various solutions. Everywhere it said to add "paged" to the array, like so:
<?php
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;**
$new_loop = new WP_Query( array(
'post_type' => 'news',
'paged' => $paged,**
'posts_per_page' => 5 // put number of posts that you'd like to display
) );
?>
However, this does not work. How can I get the pagination to work in a custom wordpress post query?
I think you're missing the argument: 'current' => max( 1, get_query_var( 'paged' ) )
After you run your loop, you can add this function in your theme(functions.php or elsewhere):
if ( ! function_exists( 'custom_pagination' ) ) {
function custom_pagination( $args = array(), $class = 'pagination' ) {
if ( $GLOBALS['wp_query']->max_num_pages <= 1 ) {
return;
}
$args = wp_parse_args(
$args,
array(
'mid_size' => 3,
'prev_next' => true,
'prev_text' => __( 'Previous', 'theme' ),
'next_text' => __( 'Next', 'theme' ),
'screen_reader_text' => __( 'Posts navigation', 'theme' ),
'type' => 'array',
'current' => max( 1, get_query_var( 'paged' ) ),
//'total' => $the_query->max_num_pages,
)
);
$links = paginate_links( $args );
?>
<nav aria-label="<?php echo $args['screen_reader_text']; ?>">
<ul class="pagination">
<?php
foreach ( $links as $key => $link ) {
?>
<li class="page-item <?php echo strpos( $link, 'current' ) ? 'active' : ''; ?>">
<?php echo str_replace( 'page-numbers', 'page-link', $link ); ?>
</li>
<?php
}
?>
</ul>
</nav>
<?php
}
}
Then finally call it in whatever template you need to:
custom_pagination();

How to add woocommerce-pagination and woocommerce-ordering dropdown to custom shortcode

I've created a custom shortcode to display products with a minimum stock amount and would like to add pagination to the results as well as calling the woocommerce-ordering dropdown to be displayed on the page.
Here's the shortcode:
// Minimum Stock Shortcode
add_shortcode( 'minimum_stock', 'minimum_stock_shortcode' );
function minimum_stock_shortcode( $atts ) {
global $woocommerce_loop;
// Attributes
$atts = shortcode_atts(
array(
'limit' => '40',
'columns' => '5',
'orderby' => 'title',
'order' => 'asc',
'category' => '',
'cat_operator' => 'IN',
'stock' => '',
),
$atts, 'minimum_stock'
);
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $atts['limit'],
'orderby' => $atts['orderby'],
'order' => $atts['order'],
'meta_query' => array(
array(
'key' => '_stock',
'value' => $atts['stock'],
'compare' => '>='
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $atts['category'],
)
)
);
ob_start();
$products = new WP_Query( $args );
$woocommerce_loop['columns'] = $atts['columns'];
if ( $products->have_posts() ) : ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php woocommerce_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
wp_reset_postdata();
return '<div class="woocommerce">' . ob_get_clean() . '</div>';
}
Any help would be very much appreciated!
Kind regards,
JP
Okay, so I've got pagination working and tidied things up a bit (it was throwing some errors in the debug log), the code now looks like this:
// Minimum Stock Shortcode
add_shortcode( 'minimum_stock', 'minimum_stock_shortcode' );
function minimum_stock_shortcode( $atts ) {
global $product, $woocommerce, $woocommerce_loop;
// Attributes
$atts = shortcode_atts(
array(
'limit' => '40',
'columns' => '5',
'orderby' => 'title',
'order' => 'asc',
'category' => '',
'cat_operator' => 'IN',
'stock' => '',
),
$atts, 'minimum_stock'
);
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $atts['limit'],
'orderby' => $atts['orderby'],
'order' => $atts['order'],
'paged' => $paged,
'meta_query' => array(
array(
'key' => '_stock',
'value' => $atts['stock'],
'compare' => '>='
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $atts['category'],
)
)
);
if ( isset( $ordering_args['meta_key'] ) ) {
$args['meta_key'] = $ordering_args['meta_key'];
}
ob_start();
$products = new WP_Query( $args );
$woocommerce_loop['columns'] = $atts['columns'];
if ( $products->have_posts() ) : ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
if($products->max_num_pages>1){
?>
<nav class="woocommerce-pagination">
<?php echo paginate_links( apply_filters(
'woocommerce_pagination_args', array(
'base' => esc_url( str_replace( 999999999, '%#%', remove_query_arg( 'add-to-cart', get_pagenum_link( 999999999, false ) ) ) ),
'format' => '',
'current' => max( 1, get_query_var( 'paged' ) ),
'total' => $products->max_num_pages,
'prev_text' => '←',
'next_text' => '→',
'type' => 'list',
'end_size' => 3,
'mid_size' => 3
)
)
);
?>
</nav>
<?php }
woocommerce_reset_loop();
wp_reset_postdata();
$return = '<div class="woocommerce columns-' . $atts['columns'] . '">' . ob_get_clean() . '</div>';
// Remove ordering query arguments
WC()->query->remove_ordering_args();
return $return;
}
Does anyone know how I can now call the woocommerce-ordering dropdown?
I've tried adding:
<?php do_action( 'woocommerce_before_shop_loop' ); ?>
But this doesn't seem to work, when I check the page it does have the 'woocommerce-notices-wrapper' but there's no sign of the 'woocommerce_catalog_ordering' that I thought should also be called with 'woocommerce_before_shop_loop'.
Any and all help will be very much appreciated :)
Update:
I found this question Adding 'sort by' drop down on custom page using woocommerce short code which gave me the answer I needed to add the woocommerce-ordering dropdown.
Here's my updated code:
// Minimum Stock Shortcode
add_shortcode( 'minimum_stock', 'minimum_stock_shortcode' );
function minimum_stock_shortcode( $atts ) {
global $woocommerce_loop;
// Attributes
$atts = shortcode_atts(
array(
'limit' => '40',
'columns' => '5',
'orderby' => 'date',
'order' => 'desc',
'category' => '',
'cat_operator' => 'IN',
'stock' => '',
), $atts );
if ( ! $atts['category'] ) {
return '';
}
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// Default ordering args
$ordering_args = WC()->query->get_catalog_ordering_args( $atts['orderby'],
$atts['order'] );
$orderby = 'date';
$order = 'desc';
if ( isset( $_GET['orderby'] ) ) {
$getorderby = $_GET['orderby'];
}
if ($getorderby == 'date') {
$orderby = 'date';
$order = 'desc';
} elseif ($getorderby == 'sku_desc') {
$orderby = 'meta_value';
$order = 'desc';
$meta_key = '_sku';
} elseif ($getorderby == 'sku_asc') {
$orderby = 'meta_value';
$order = 'asc';
$meta_key = '_sku';
}
$args = array(
'post_type' => array( 'product', 'product_variation' ),
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $atts['limit'],
'orderby' => $orderby, // $ordering_args['orderby'],
'order' => $order, // $ordering_args['order'],
'paged' => $paged,
'meta_query' => array(
array(
'key' => '_stock',
'value' => $atts['stock'],
'compare' => '>='
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $atts['category'],
)
)
);
if ( isset( $ordering_args['meta_key'] ) ) {
$args['meta_key'] = $ordering_args['meta_key'];
}
ob_start();
$products = new WP_Query( $args );
$woocommerce_loop['columns'] = $atts['columns'];
if ( $products->have_posts() ) : ?>
<div style="width:100%;">
<div style="float:right">
<form class="woocommerce-ordering" method="get">
<select name="orderby" class="orderby">
<?php
$catalog_orderby = apply_filters( 'woocommerce_catalog_orderby', array(
'date' => __( 'Sort by latest', 'woocommerce' ),
'sku_asc' => __( 'A-Z / Low to High Numbers', 'woocommerce' ),
'sku_desc' => __( 'Z-A / High to Low Numbers', 'woocommerce' )
) );
foreach ( $catalog_orderby as $id => $name )
echo '<option value="' . esc_attr( $id ) . '" ' . selected( $getorderby, $id, false ) . '>' . esc_attr( $name ) . '</option>';
?>
</select>
<?php
// Keep query string vars intact
foreach ( $_GET as $key => $val ) {
if ( 'orderby' === $key || 'submit' === $key )
continue;
if ( is_array( $val ) ) {
foreach( $val as $innerVal ) {
echo '<input type="hidden" name="' . esc_attr( $key ) . '[]" value="' . esc_attr( $innerVal ) . '" />';
}
} else {
echo '<input type="hidden" name="' . esc_attr( $key ) . '" value="' . esc_attr( $val ) . '" />';
}
}
?>
</form>
</div>
</div>
<div style="clear:both;"></div>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
if($products->max_num_pages>1){
?>
<nav class="woocommerce-pagination">
<?php echo paginate_links( apply_filters(
'woocommerce_pagination_args', array(
'base' => esc_url( str_replace( 999999999, '%#%', remove_query_arg( 'add-to-cart', get_pagenum_link( 999999999, false ) ) ) ),
'format' => '',
'current' => max( 1, get_query_var( 'paged' ) ),
'total' => $products->max_num_pages,
'prev_text' => '←',
'next_text' => '→',
'type' => 'list',
'end_size' => 3,
'mid_size' => 3
)
)
);
?>
</nav>
<?php }
woocommerce_reset_loop();
wp_reset_postdata();
$return = '<div class="woocommerce columns-' . $atts['columns'] . '">' . ob_get_clean() . '</div>';
// Remove ordering query arguments
WC()->query->remove_ordering_args();
return $return;
}
I hope someone might find this helpful :)
Kind regards,
JP

Resources