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.
Related
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
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.
I tried to load more posts using ajax. I see there is lot of plugins and solutions in online and stackoverflow. But none of work for me. Actually I want to do this without plugin. So I can use this in different page archive or different page template where I need this code.
Here is my code that I got from another question in stackoverflow. My score is lower, so I can't comment out there.
Here is my index.php code:
<?php get_header(); ?>
<div class="ajax-posts">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<h2><?php the_title(); ?></h2>
<?php
endwhile;
echo '<a id="more_posts" href="#">Load More</a>';
wp_reset_postdata();
?>
</div>
<script type="text/javascript">
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
var page = 1;.
var ppp = 3;
$("#more_posts").on("click",function(){
$("#more_posts").attr("disabled",true);
$.post(ajaxUrl, {
action:"more_post_ajax",
offset: (page * ppp) + 1,
ppp: ppp
}).success(function(posts){
page++;
$(".ajax-posts").append(posts); // CHANGE THIS!
$("#more_posts").attr("disabled",false);
});
});
</script>
<?php get_footer(); ?>
Here is functions.php code
<?php
function more_post_ajax(){
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
header("Content-Type: text/html");
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'offset' => $offset,
);
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
the_title();
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
?>
I don't know why posts not load or not work load more link. I hope someone will be help.
Ref: https://stackoverflow.com/a/31588401/5545813
The better way is to return an array with ur post title. Then display them after the success. If the array length < ppp (there is no more post).
$array_return = array();
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
$content = "<h1>" . get_the_title() . "</h1>";
$content .= "<div>" . get_the_content() . "</div>";
$content .= "<div>" . get_field("your_field") . "</div>";
$array_return[] = $content;
}
echo json_encode( $array_return );
die();
In your js script,
var posts = JSON.parse(posts);
for( var i = 0; i < posts.length; i++ )
$(".ajax-posts").append(posts[i]);
if( posts.length < ur_ppp )
$("#more_posts").fadeOut();
Something like that
I want to paginate my WordPress posts in a custom loop with Ajax, so when I click on load more button posts will appear.
My code:
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 1
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<h1><?php the_title(); ?></h1>
<p>
<?php the_content(); ?>
</p>
<?php
endwhile;
echo 'Load More';
wp_reset_postdata();
?>
This code does not paginate. Is there a better way to do this?
The Load More button needs to send a ajax request to the server and the returned data can be added to the existent content using jQuery or plain javascript. Assuming your using jQuery this would starter code.
Custom Ajax Handler (Client-side)
Load More
Change to:
<a id="more_posts" href="#">Load More</a>
Javascript: - Put this at the bottom of the file.
//</script type="text/javascript">
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
var page = 1; // What page we are on.
var ppp = 3; // Post per page
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
$.post(ajaxUrl, {
action:"more_post_ajax",
offset: (page * ppp) + 1,
ppp: ppp
}).success(function(posts){
page++;
$(".name_of_posts_class").append(posts); // CHANGE THIS!
$("#more_posts").attr("disabled",false);
});
});
//</script>
Custom Ajax Handler (Server-side)
PHP - Put this in the functions.php file.
function more_post_ajax(){
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
header("Content-Type: text/html");
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 1,
'offset' => $offset,
);
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
the_content();
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
I want to create a slider but i can't get the post excerpt working. The title and permalink are working but the excerpt won't show... here is my code:
// Args
$args = array(
'cat' => $categories,
'post_type' => 'post',
'posts_per_page' => $amount,
);
// Our incrementing counter, leave this set to 0
$counter = 0;
// Query the posts based off of the parameters in the $args variable
$bs_posts = new WP_Query( $args );
// Our calculated limit of how many posts we have to work with, don't change this
$bs_posts_limit = count( $bs_posts->posts ) - 1;
// How many posts to display in each slide of the SlideDeck
$per_page = !empty($this->options['per-slide']) ? $this->options['per-slide'] : '2';
// Add "active" class to 1st slider item
$j=1;
// Carousel/Slider Html
echo "$tab<div" . (!empty($this->options['id']) ? ' id="slider-' . trim($thesis->api->esc($this->options['id'])) . '"' : '') . ' class="carousel slide'. (!empty($this->options['c-type']) ? ' ' . trim($thesis->api->esc($this->options['c-type'])) : '') .''. (!empty($this->options['class']) ? ' ' . trim($thesis->api->esc($this->options['class'])) : '') . "\" data-ride=\"carousel\">\n".
"$tab<h2 class=\"text-shadow\">". stripslashes($this->options['intro']) ."</h2>\n".
"$tab<div class=\"carousel-inner\">\n";
?>
<?php foreach( $bs_posts->posts as $bs_post ): ?>
<?php
// Variables
$slide_number = floor( $counter / $per_page ) + 1;
$slide_mod = $counter % $per_page;
$bs_post_ID = $bs_post->ID;
$bs_post_title = get_the_title( $bs_post_ID );
$bs_post_link = get_permalink( $bs_post_ID );
$bs_post_excerpt = get_the_excerpt( $bs_post_ID );
?>
<?php if( $slide_mod == 0 ): ?>
<div class="item <?php if($j <= 1) {echo 'active';} ?>">
<?php endif; ?>
<div class="single">
<?php if (has_post_thumbnail( $bs_post->ID )) the_post_thumbnail( 'thumbnail', array( 'title' => "#htmlcaption") ) ?>
<?php echo $bs_post_title;?>
<?php echo $bs_post_excerpt; ?>
Read More
</div>
<?php if( $slide_mod == ( $per_page - 1 ) || $counter == $bs_posts_limit ): ?>
</div>
<?php endif; ?>
<?php $counter++; $j++;?>
<?php endforeach; ?>
<?
echo "$tab</div>\n".
"$tab</div>\n";
?>
<?
I want to create a slider based on bootstrap carousel plugin. Actualy i want to appear 2-3 or more posts per slide as you see and I succeded that but the slide only shows the post title and the post permalink. The excerpt and image won't work so please help me
After looking at the docs, I see that get_the_excerpt() does not take a post id parameter. It must be used within the lop.
http://codex.wordpress.org/Function_Reference/get_the_excerpt
If you want to get the excerpt outside of the loop, you will have to get the full content of the post and truncate it yourself.