Custom Pagination for Posts not working after page 11 - php

I have created a section on home where i am showing 6 post starting from offset 3 and below that i add a custom pagination code.
I have total 93 published post and as i set offset 3 so the pagination is set for rest 90 posts.
For 90 posts, total number of links is 15 in pagination.
Pagination works fine till 11 page i.e mysiteurl/page/11. when i click 12 in the pagination links, it show me 404. It should show me next 6 posts.
Here is my code:
<?php
// function to get page number
function get_url_var($name){
$strURL = $_SERVER['REQUEST_URI'];
$arrVals = split("/",$strURL);
$found = 0;
foreach ($arrVals as $index => $value){
if($value == $name) $found = $index;
}
$place = $found + 1;
return $arrVals[$place];
}
function myprefix_query_offset(&$query) {
//Before anything else, make sure this is the right query...
if ( ! $query->is_home() ) {
return;
}
//First, define your desired offset...
$offset = 3;
//Next, determine how many posts per page you want (we'll use WordPress's settings)
$ppp = 6;
$page = get_url_var('page');
//Next, detect and handle pagination...
if ( $page ) {
//Manually determine page query offset (offset + current page (minus one) x posts per page)
$page_offset = $offset + ( ($page-1) * $ppp );
//Apply adjust page offset
$query->set('offset', $page_offset );
}
else {
//This is the first page. Just use the offset...
$query->set('offset',$offset);
}
}
add_action('pre_get_posts', 'myprefix_query_offset', 1 );
function myprefix_adjust_offset_pagination($found_posts, $query) {
//Define our offset again...
$offset = 3;
//Ensure we're modifying the right query object...
if ( $query->is_home() ) {
//Reduce WordPress's found_posts count by the offset...
return $found_posts - $offset;
}
return $found_posts;
}
add_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );
$page = get_url_var('page');
$paged = ( $page ) ? $page : 1;
if($paged == 1){
$custom_args = array(
'post_type' => 'post',
'posts_per_page' => 6,
'paged' => $paged,
'offset' => 3,
'post_status' => 'publish'
);
}else{
$custom_args = array(
'post_type' => 'post',
'posts_per_page' => 6,
'paged' => $paged,
'offset' => 3 + ( ($paged-1) * 6),
'post_status' => 'publish'
);
}
$wpb_ll_query = new WP_Query( $custom_args );
if ( $wpb_ll_query->have_posts() ) : while ( $wpb_ll_query->have_posts() ) : $wpb_ll_query->the_post();
?>
<div class="col-lg-4 col-sm-6 col-md-4 col-xs-6 rec-first1">
<a href="
<?php the_permalink();?>">
<div class="grid-latest-posts">
<?php
if(has_post_thumbnail())
{
the_post_thumbnail();
}
else
{
?>
<img class="no-image" src="/wp-content/uploads/2017/02/no-image.png">
<?php
}
$category_object = get_the_category(get_the_ID());
$category_name = $category_object[0]->name;
?>
<label><?php echo $category_name;?></label>
</div>
</a>
<div class="style-txt-nxt">
<span> <a href="<?php the_permalink();?>">
<?php
$string = get_the_title();
$post_title = (strlen($string) > 30) ? substr($string,0,30)."..." : $string;
?>
<?php
echo $post_title;
?>
</a></span>
<p id="art-date2">
<?php echo get_the_date(); ?></p>
<div class="line1">
</div>
<h3>
<a href="
<?php the_permalink();?>">read more</a>
</h3>
</div>
</div>
<?php
endwhile;
//wp_reset_postdata();
else : ?>
<p>
<?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
</div>
</div>
</section>
<!-- Pagination for posts -->
<section>
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<!--<h3><a id="more_posts">Load More</a></h3>-->
<?php
if (function_exists(custom_pagination)) {
custom_pagination($wpb_ll_query->max_num_pages,"",$paged);
}
wp_reset_postdata();
?>
</div>
</div>
</div>
</section>
I defined custom_pagination() function in function.php
<?php
function custom_pagination($numpages = '', $pagerange = '', $paged='') {
if (empty($pagerange)) {
$pagerange = 2;
}
/**
* This first part of our function is a fallback
* for custom pagination inside a regular loop that
* uses the global $paged and global $wp_query variables.
*
* It's good because we can now override default pagination
* in our theme, and use this function in default queries
* and custom queries.
*/
global $paged;
if (empty($paged)) {
$paged = 1;
}
if ($numpages == '') {
global $wp_query;
$numpages = $wp_query->max_num_pages;
if(!$numpages) {
$numpages = 1;
}
}
/**
* We construct the pagination arguments to enter into our paginate_links
* function.
*/
$pagination_args = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => False,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => True,
'prev_text' => __('«'),
'next_text' => __('»'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<nav class='custom-pagination'>";
echo "<span class='page-numbers page-num'>Page " . $paged . " of " . $numpages . "</span> ";
echo $paginate_links;
echo "</nav>";
}
}?>
Can anyone suggest me some solution to fix it.

Related

How to display loop by custom acf fields with pagination?

I ordered a service from a freelancer, he disappeared, now I'm trying to figure it out myself.
Please help me figure out what the problem might be.
He did loop and pagination by ACF custom field on the page. When the page loads, only pagination is displayed. not the field. When you click on any page switching button, the fields are displayed. Here is the link to the page
http://alex13746.beget.tech/klienty/
Here is the code
<div class="p-client">
<div class="p-client__items">
<?php
if( get_query_var('n') ) {
$page = $_GET['n'];
} else {
$page = $_GET['n'];
}
// Variables
$row = 0;
$images_per_page = 9;
$images = get_field( 'clients' );
$total = count( $images );
$pages = ceil( $total / $images_per_page );
$min = ( ( $page * $images_per_page ) - $images_per_page ) + 1;
$max = ( $min + $images_per_page ) - 1;
if( have_rows('clients') ):
while ( have_rows('clients') ) : the_row();
$row++;
// Ignore this image if $row is lower than $min
if($row < $min) { continue; }
// Stop loop completely if $row is higher than $max
if($row > $max) { break; } ?>
<div class="p-client__item">
<div class="p-client__img">
<img src="<?php $img=get_sub_field('img'); echo $img['url'];?>" alt="">
</div>
<p class="p-client__name"><?php the_sub_field('title');?></p>
</div>
<?php
endwhile; ?>
<?php
endif;
?>
</div>
<div class="pagin_wrap" style="margin-left:15px;">
<?php
// Pagination
echo paginate_links( array(
'base' => get_permalink() . '?n=%#%',
'format' => '?n=%#%',
'current' => $page,
'total' => $pages
) ); ?>
</div>
</div>

Adding pagination to my custom blog page using a foreach post loop

I built a custom blog page in my custom wordpress theme, and I'm trying to add pagination to the blog page. Im' using a foreach loop, instead your standard "if while post" loop.
Everything is working find, however I'm not sure where to add "paged" as an argument.
Here is my code:
<?php if (is_page( 'Blog' )) : ?>
<?php
//Get the Posts
$posts = get_posts();
foreach ($posts as $post) :
setup_postdata( $post );
//Setup Post data
$haystack = get_the_category($post->ID);
$i = count($haystack);
$string = "";
for ($j=0; $j < $i; $j++) {
$string .= " ";
$string .= $haystack[$j]->slug;
}
$link = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large', false );
$href = get_the_permalink();
$theCat = wp_get_post_categories($post->ID);
if (has_post_thumbnail($post->ID)){
$theCols = 'span12';
$imgWidth = 'span4';
$contentWidth = 'span8';
} else {
$theCols = 'span12';
$imgContainer ='display: none;';
$contentWidth = 'width: 100%;';
}
?>
<div class="<?php echo $string;?>">
<div id="post-<?php the_ID(); ?>" class="post-content <?php echo $theCols;?> group nopad">
<div class="post-content--image <?php echo $imgWidth;?> <?php echo $imgContainer;?>">
<img src="<?php echo $link[0]; ?>">
</div>
<!-- Post Content -->
<div class="post-content--container <?php echo $contentWidth;?>">
<?php
$post_title = get_the_title();
$post_title = explode(' ', $post_title);
$title = '';
for ($i=0; $i < 5 ; $i++) {
$title .= $post_title[$i];
$title .= ($i == 50) ? "..." : " ";
}
?>
<p class="post-content--date"><?php echo get_the_date('d M Y'); ?></p>
<h4 class="post-content--heading"><?php echo $title;?></h4>
<p class="post-content--cat"><?php echo $string;?></p>
<div class="post-content--text">
<?php
if ($theCat){
$str = substr(get_the_excerpt(), 0,255);
} else {
$str = get_the_excerpt();
}
$n = strpos($str, '<a');
if ($n > 0){
$rest = substr($str, 0, $n);
echo $rest;
} else {
echo $str;
}
?> ...
</div>
<button class="see-more-btn">Read More</button>
</div>
</div>
</div>
<?php endforeach;
wp_reset_postdata();?>
<?php else : ?>
<p>Critiria Not Found</p>
<?php endif; ?>
what am I missing? Thanks for the help in advance.
If you are going to use the get_posts function you need to set the posts_per_page and offset parameters. You need to check the current page and set the offset according to how many posts you are showing per page and the current page. For eg. On Page 2 and showing 5 posts per page you need to set the offset to 5 in order to skip the first 5 posts.
Note: The posts_per_page parameter does NOT work without setting the offset parameter.
$args = array(
'posts_per_page' => 5,
'offset' => 0
);
$posts_array = get_posts( $args );
One other way is to use the WP_Query and instead of passing the offset argument you just pass the page argument only like the example below where get_query_var('paged') get the value of the ?paged=x and if it its not set will default to '1'.
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query = new WP_Query( array( 'paged' => $paged ) );
If you are going to use WP_Query you need to change from foreach to:
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$post_id = get_the_ID();
$haystack = get_the_category($post_id);
$i = count($haystack);
}
}
To output the pagination links after the WP_Query you can use the paginate_links function as below. The advantage of using WP_Query is that you will also get the total number of posts found matching the current query parameters in found_posts and other values which you might need like max_num_pages.
echo paginate_links( array(
'base' => '%_%',
'total' => $query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => false,
'prev_next' => true,
'prev_text' => __('« Previous'),,
'next_text' => __('Next »'),
'add_args' => false,
'add_fragment' => '',
) );
get_posts: https://codex.wordpress.org/Template_Tags/get_posts
WP_Query: https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters
paginate_links: https://codex.wordpress.org/Function_Reference/paginate_links

custom wpdb query with post per page?

I need help for this piece of code:
<?php
global $wpdb;
$id = get_the_ID();
$querystring = "SELECT * FROM wp_candle WHERE id = $id";
$results = $wpdb->get_results( $querystring ,OBJECT);
foreach($results as $result)
{
echo
'<div class="kerzenbox clearfix">
<article class="post boxrechts" id="">
<h2> "'.$result->contactName.'" </h2>
<p> "'.$result->worte.'" </p>
<img src="myImagePath" width="50" height="70"/>
</article>
</div>';
}
?>
I need the post per page option implemented but I don't know how. Without post per page for this specific query the page looks really weird.
<?php
global $wpdb;
$rows_per_page = 8;
$current = (intval(get_query_var('paged'))) ? intval(get_query_var('paged')) : 1;
$rows = $wpdb->get_results("SELECT * FROM wp_candle WHERE id = $id ");
global $wp_rewrite;
$pagination_args = array(
'base' => #add_query_arg('paged','%#%'),
'format' => '',
'total' => ceil(sizeof($rows)/$rows_per_page),
'current' => $current,
'show_all' => false,
'type' => 'plain',
);
if( $wp_rewrite->using_permalinks() )
{
$pagination_args['base'] = user_trailingslashit( trailingslashit( remove_query_arg('s',get_pagenum_link(1) ) ) . 'page/%#%/', 'paged');
}
if( !empty($wp_query->query_vars['s']) )
{
$pagination_args['add_args'] = array('s'=>get_query_var('s'));
}
echo paginate_links($pagination_args);
?>

Wordpress: Add Infinite Scrolling Pagination

I'm very new to the Wordpress. I'm currently using the FoundationPress theme and I'm trying to add a button that the user can click to load more post.
What I want is that initially the user will see four blog posts and when the user click on the read more button it will load the next four until there are no more posts and the button disappear.
I got up to the point where I can load the first four posts, but I'm having a hard time setting up a button to display the next four posts.
This is what I have so far:
<section class="row blogArticleWrapper">
<?php while ( have_posts() ) : the_post(); ?>
<?php
the_post();
$blog_posts = get_posts( array(
'post_type' => 'blog',
'posts_per_page' => 4,
'offset' => 1,
'orderby' => 'date',
'order' => 'DESC'
) );
if ( $blog_posts ):
?>
<?php
foreach ( $blog_posts as $post ):
setup_postdata($post);
?>
<article class="blog-profile small-12 columns">
<span class="name"><?php the_field("news_title"); ?></span>
<p class="writtenBy">Written by: <?php the_field("news_written_by"); ?> <span class="date">Date: <?php the_field("news_date"); ?></span></p>
</article><!-- /.profile -->
<?php endforeach;
?>
<?php endif; ?>
<?php endwhile; // end of the loop. ?>
</section><!-- /.row -->
I tried following this guide, but I don't know how to use it on my page.
Any help is appreciated,
Thanks.
Remove:
while ( have_posts() ) : the_post(); ?>
the_post();
and
<?php endwhile; // end of the loop. ?>
Change request to
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$blog_posts = get_posts( array(
'post_type' => 'blog',
'posts_per_page' => 4,
'offset' => 1,
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC'
) );
Add to functions.php
function wp_corenavi() {
global $wp_query;
$pages = '';
$max = $wp_query->max_num_pages;
if (!$current = get_query_var('paged')) $current = 1;
$a['base'] = str_replace(999999999, '%#%', get_pagenum_link(999999999));
$a['total'] = $max;
$a['current'] = $current;
$total = 1;
$a['mid_size'] = 3;
$a['end_size'] = 1;
$a['prev_text'] = '«';
$a['next_text'] = '»';
if ($max > 1) echo '<div id="pagination" class="navigation column medium-12">';
if ($total == 1 && $max > 1) $pages = '<span class="pages">' . __('Page', 'Site') . $current . ' ' . __('of', 'Site') . ' ' . $max . '</span>'."\r\n";
echo $pages . paginate_links($a);
if ($max > 1) echo '</div>';
}
Add after endforeach; - wp_corenavi();wp_reset_postdata();;
Then jQuery ajax:
//Trigger ajax at the end of page
$(window).scroll(function(){
var top = $('body,html').scrollTop();
var height = $(window).height();
var docheight = $(document).height();
var screen = Number(docheight) - Number(height);
if( top >= screen ){
$('#pagination .next').click();
}
});
//do ajax on pagination
$('#pagination .next').on('click',function(e){
e.preventDefault();
$('#pagination').remove();
$.ajax({
type: "GET",
url: $(this).attr('href'),
dataType: "html",
success: function(out){
//We get blocks from next page , change selector to yours
result = $(out).find('.short-articles-wrapper-main .short-article');
//find next page pagination,change selector to yours
pagination = $(out).find('.short-articles-wrapper-main #pagination');
//append blocks from next page to current ,change selector to yours
$('.short-articles-wrapper-main').append(result);
//append pagination from next page to current, change selector to yours
$('.short-articles-wrapper-main').append(pagination.fadeIn(200));
}
});
});
Hope it will help you.

How add condition in wordpress shortcode loop

I want to multiple of 2 close div and open a new div in wp loop using shortcode post loop.
if($i % 2 == 0) {echo '</li><li>';}
$i++;
How Can do it?
General loop:
<?php
$i = 1;
//added before to ensure it gets opened
echo '<li>';
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
// post stuff...
?>
<div class="frCol"><?php the_post_thumbnail('thumbnail', array('class' => 'imgthumb')); ?>
<div class="item-info">
<h2><?php the_title(); ?></h2>
</div>
</div>
<?php
// if multiple of 3 close div and open a new div
if($i % 2 == 0) {echo '</li><li>';}
$i++; endwhile; endif;
//make sure open div is closed
echo '</li>';
?>
This is the shortcode:
function testimonial_thumb_shortcode($atts){
extract(shortcode_atts(array(
'category' => ''
), $atts));
$q = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'testimonials',
'testimonial_cat' => $category
));
$list = ' <ul>';
while($q->have_posts()):
$q->the_post();
$idd = get_the_ID();
$author_photo = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail');
$list .= '/*Main loop*/';
endwhile;
$list.= '</ul>';
wp_reset_query();
return $list;
}
add_shortcode('tthumb', 'testimonial_thumb_shortcode');
Based on your comment, maybe this helps:
function testimonial_thumb_shortcode($atts){
extract(shortcode_atts(array(
'category' => ''
), $atts));
$q = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'testimonials',
'testimonial_cat' => $category
));
$list = ' <ul><li>';
$i = 0; //init the counter
while($q->have_posts()):
$q->the_post();
$idd = get_the_ID();
$author_photo = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail');
$list .= '/*Main loop*/';
$i++; //increase counter
if($i % 2 == 0){
$list .= '</li><li>';
}
endwhile;
$list.= '</li></ul>';
wp_reset_query();
return $list;
}
add_shortcode('tthumb', 'testimonial_thumb_shortcode');

Categories