John Davidson

php - Pagination for Wordpress Custom Theme

0 comments
Message:


i am working on a news page in my custom theme, and i need to put pagination on it. I tried everything, but it doesnt seem to be working. Could someone help me with the pagination, but have to do it with qustom queries, so i can fetch post thumbnail, title and link to it.


$atts = shortcode_atts( array(
'post_type' => 'post',
'posts_per_page'=> 4,
'category_name'=> 'news',
'featured' => 'false',
'sidebar'=> 'false'
), $atts );

$the_query = new WP_Query($atts);
while($the_query->have_posts()) {
$the_query->the_post(); ?>
<div class="col-md col-xl-6">
<div class=" mt-2 mb-2">
<a href="#">
<div class="latest-news__wrapper">
<div class=" lazyloaded">
<?php if(get_the_post_thumbnail()){
echo get_the_post_thumbnail('',['class' => ' latest-news__thumbnail']);
}else{
echo '<img class=" rounded-3 latest-news__thumbnail" src="'. site_url() . '/wp-content/uploads/2022/08/da084e01-7cae-3ee6-8b2e-1f0e76fd397f.jpg'.'" alt="" />';
}?>
</div>
<div class="latest-news__info">
<div class="latest-news__date"><?php the_time('j F, Y') ?></div>
<h4 class="latest-news__title text-color-5 lines-2">
<?php
if (strlen(the_title('','',FALSE)) > 30) {
$title_short = substr(the_title('','',FALSE), 0, 30);
preg_match('/^(.*)\s/s', $title_short, $matches);
if ($matches[1]) $title_short = $matches[1];
$title_short = $title_short.' ...';
} else {
$title_short = the_title('','',FALSE);
}
echo $title_short;

?>
</h4>
</div>
</div>
</a>
</div>
</div>

<?php

}


My Answer:
'news',
'posts_per_page' => 5,
'paged' => 1
), $atts );

$paged = get_query_var('paged') ? get_query_var('paged') : 1;

$args = array(
'post_type' => $atts['post_type'],
'posts_per_page' => $atts['posts_per_page'],
'paged' => $paged
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Display post thumbnail, title, and link here
}

// Pagination
echo paginate_links( array(
'total' => $query->max_num_pages
) );
}

wp_reset_postdata();

In this code snippet, we first define the attributes for the shortcode, including the post type and number of posts per page. We then get the current page number using get_query_var and set up the query arguments. We run the query and loop through the posts to display the post thumbnail, title, and link.

Finally, we add pagination using the paginate_links function, passing in the total number of pages from the query. Don't forget to reset the post data after the loop.

Rate this post

4 of 5 based on 8639 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us