Snippets Collections
<?php
    /* Template Name: Blog Template 2 */
?>
<?php get_header(3); ?>
<?php 
    $blog_subtitle = get_field("blog_subtitle");
    $time_read = get_field("time_read");
?>
<div class="main blog-page">
    <div class="container">
        <div class="page-header">
            <h1 class="blog-title"><?php the_title(); ?></h1>
            <?php if(!empty($blog_subtitle)): ?>
            <p class="blog-subtitle"><?php echo $blog_subtitle ?></p>
            <?php endif; ?>
        </div>

        <!-- Swiper Container -->
        <div class="swiper-container swiper-category">
            <div class="swiper-wrapper">
                <div class="swiper-slide"><a href="#" class="category-btn" data-category="all" data-active="true">All</a></div>
                
                <?php 
                $categories = get_categories(array(
                    'hide_empty' => false, 
                ));

                foreach ($categories as $category) :
                    if ($category->slug !== 'uncategorized') :
                ?>
                        <div class="swiper-slide"><a href="#" class="category-btn" data-category="<?php echo $category->slug; ?>"><?php echo $category->name; ?></a></div>
                <?php 
                    endif;
                endforeach; 
                ?>
            </div>

            <div class="swiper-button-next">
                <img src="https://stillviral.com/wp-content/uploads/2025/03/arrow-right-circle_svgrepo.com-1-1.svg" alt="Next">
            </div>
            <div class="swiper-button-prev">
                <img src="https://stillviral.com/wp-content/uploads/2025/03/arrow-right-circle_svgrepo.com-1-2.svg" alt="Previous">
            </div>
        	</div>

        
        <!-- Post Container -->
        <div id="post-container" class="post-container">
            <?php
            $args = array(
                'post_type' => 'post',
                'posts_per_page' => 10, 
                'paged' => get_query_var('paged') ? get_query_var('paged') : 1, 
            );
            $query = new WP_Query($args);

            if ($query->have_posts()) :
                while ($query->have_posts()) : $query->the_post();
                    $category = get_the_category()[0]->name; 
                    $category_class = strtolower(str_replace(' ', '-', $category)); 
            ?>
                <div class="post-card <?php echo esc_attr($category_class); ?>">
                    <div class="post-header">
                        <img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_title(); ?>" class="post-feature-image">
                    </div>
                    <div class="post-info">
                    	<?php
						$category = get_the_category();
						$brand_color = '';
						$color_class = 'color-default';
						$time_read = get_field('time_read');

						if (!empty($category)) {
							$category_id = $category[0]->term_id;
							$brand_color = get_field('brand_color', 'category_' . $category_id); 

							if ($brand_color) {
								$color_class = 'color-' . esc_attr($brand_color);
							}
						}
						?>
						<div class="post-meta">
							<?php if ($category || $time_read): ?>
								<?php if ($category): ?>
									<span class="category <?php echo esc_attr($color_class); ?>">
										<?php echo esc_html($category[0]->name); ?>
									</span>
								<?php endif; ?>
								<?php if ($time_read): ?>
									<span class="time-read">
										<?php if ($category); ?>
										<?php echo esc_html($time_read); ?>
									</span>
								<?php endif; ?>
							<?php endif; ?>
						</div>

                        <h3><?php the_title(); ?></h3>
						<div class="author-posted">
							<div class="author-info">
								<img src="<?php echo get_avatar_url(get_the_author_meta('ID')); ?>" alt="Author Avatar" class="author-avatar">
								<span class="author-name"><?php the_author(); ?></span>
							</div>
							<div class="post-time">
								<span>Last Update: <?php the_modified_date(); ?></span>
							</div>
						</div>
                        
                        <a href="<?php the_permalink(); ?>" class="post-link">Learn More</a>
                    </div>
                </div>
            <?php
                endwhile;
                wp_reset_postdata();
            else :
                echo '<p>No posts found.</p>';
            endif;
            ?>
        </div>
        
        <div class="pagination">
			<?php
			$current_page = max(1, get_query_var('paged')); 
			$total_pages  = $query->max_num_pages;

			$pagination = paginate_links(array(
				'total'     => $total_pages,
				'current'   => $current_page,
				'prev_text' => '<img src="https://stillviral.com/wp-content/uploads/2025/03/Icon.svg" alt="Previous" class="pagination-icon prev">',
				'next_text' => '<img src="https://stillviral.com/wp-content/uploads/2025/03/Icon.svg" alt="Next" class="pagination-icon next">',
				'type'      => 'array',
			));

			echo '<nav>';

			if ($current_page == 1) {
				echo '<span class="pagination-disabled prev">
						<img src="https://stillviral.com/wp-content/uploads/2025/03/Icon.svg" alt="Previous" class="pagination-icon prev">
					  </span>';
			}

			foreach ($pagination as $link) {
				echo $link;
			}

			if ($current_page == $total_pages) {
				echo '<span class="pagination-disabled next">
						<img src="https://stillviral.com/wp-content/uploads/2025/03/Icon.svg" alt="Next" class="pagination-icon next">
					  </span>';
			}

			echo '</nav>';
			?>
		</div>
    </div>
</div>

<?php get_footer(3); ?>
jQuery(document).ready(function($) {
    console.log(ajax_object);

    const categoryButtons = $('.category-btn');
    const postContainer = $('#post-container');
    const paginationContainer = $('.pagination');
    let currentCategory = 'all';

    function filterPosts(category, page) {
        $.ajax({
            url: ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'filter_posts',
                category: category,
                paged: page
            },
            success: function(response) {
                postContainer.html(response.posts);

                updatePagination(response.total_pages, response.current_page, category);
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', status, error);
            }
        });
    }
	
    function updatePagination(totalPages, currentPage, category) {
        let paginationHtml = '<nav>';

        if (currentPage == 1) {
            paginationHtml += '<span class="pagination-disabled prev"><img src="https://stillviral.com/wp-content/uploads/2025/03/Icon.svg" alt="Previous" class="pagination-icon prev"></span>';
        } else {
            paginationHtml += '<a href="#" class="page-link prev" data-page="' + (currentPage - 1) + '"><img src="https://stillviral.com/wp-content/uploads/2025/03/Icon.svg" alt="Previous" class="pagination-icon prev"></a>';
        }

        for (let i = 1; i <= totalPages; i++) {
            if (i == currentPage) {
                paginationHtml += '<span class="current">' + i + '</span>';
            } else {
                paginationHtml += '<a href="#" class="page-link" data-page="' + i + '">' + i + '</a>';
            }
        }

        if (currentPage == totalPages) {
            paginationHtml += '<span class="pagination-disabled next"><img src="https://stillviral.com/wp-content/uploads/2025/03/Icon.svg" alt="Next" class="pagination-icon next"></span>';
        } else {
            paginationHtml += '<a href="#" class="page-link next" data-page="' + (currentPage + 1) + '"><img src="https://stillviral.com/wp-content/uploads/2025/03/Icon.svg" alt="Next" class="pagination-icon next"></a>';
        }

        paginationHtml += '</nav>';
        paginationContainer.html(paginationHtml);
    }

    categoryButtons.on('click', function(e) {
        e.preventDefault();
        const category = $(this).data('category');
        currentCategory = category;

        categoryButtons.removeAttr('data-active');
        $(this).attr('data-active', 'true');

        filterPosts(category, 1);
    });

    paginationContainer.on('click', '.page-link', function(e) {
        e.preventDefault();
        const page = $(this).data('page');
        filterPosts(currentCategory, page);
    });
});
// AJAX BLOG PAGE
add_action('wp_ajax_filter_posts', 'filter_posts_callback');
add_action('wp_ajax_nopriv_filter_posts', 'filter_posts_callback');

function filter_posts_callback() {
    $category = isset($_POST['category']) ? sanitize_text_field($_POST['category']) : 'all';
    $paged = isset($_POST['paged']) ? intval($_POST['paged']) : 1;

    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 10,
        'paged' => $paged,
    );

    if ($category !== 'all') {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => $category,
            ),
        );
    }

    $query = new WP_Query($args);

    ob_start();
    if ($query->have_posts()) :
        while ($query->have_posts()) : $query->the_post();
            $category = get_the_category();
            $brand_color = '';
            $color_class = 'color-default';
            $time_read = get_field('time_read');

            if (!empty($category)) {
                $category_id = $category[0]->term_id;
                $brand_color = get_field('brand_color', 'category_' . $category_id);

                if ($brand_color) {
                    $color_class = 'color-' . esc_attr($brand_color);
                }
            }
            ?>
            <div class="post-card <?php echo esc_attr(strtolower(str_replace(' ', '-', get_the_category()[0]->name))); ?>">
                <div class="post-header">
                    <img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_title(); ?>" class="post-feature-image">
                </div>
                <div class="post-info">
                    <div class="post-meta">
                        <?php if ($category || $time_read): ?>
                            <?php if ($category): ?>
                                <span class="category <?php echo esc_attr($color_class); ?>">
                                    <?php echo esc_html($category[0]->name); ?>
                                </span>
                            <?php endif; ?>
                            <?php if ($time_read): ?>
                                <span class="time-read">
                                    <?php if ($category); ?>
                                    <?php echo esc_html($time_read); ?>
                                </span>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                    <h3><?php the_title(); ?></h3>
                    <div class="author-posted">
                        <div class="author-info">
                            <img src="<?php echo get_avatar_url(get_the_author_meta('ID')); ?>" alt="Author Avatar" class="author-avatar">
                            <span class="author-name"><?php the_author(); ?></span>
                        </div>
                        <div class="post-time">
                            <span>Last Update: <?php the_modified_date(); ?></span>
                        </div>
                    </div>
                    <a href="<?php the_permalink(); ?>" class="post-link">Learn More</a>
                </div>
            </div>
            <?php
        endwhile;
        wp_reset_postdata();
    else :
        echo '<p>No posts found.</p>';
    endif;
    $posts_html = ob_get_clean(); 

    $total_pages = $query->max_num_pages;

    wp_send_json(array(
        'posts' => $posts_html,
        'total_pages' => $total_pages,
        'current_page' => $paged,
    ));

    wp_die();
}
const paginate = (array) => {
  const itemsPerPage = 10;
  const numberOfPages = Math.ceil( array.length / itemsPerPage);

  // need to create an array of arrays [[10], [20], [30]] etc
  return Array.from({ length: numberOfPages }, (_, pageIndex) => {
    const startIndex = pageIndex * itemsPerPage;
    return array.slice(startIndex, startIndex + itemsPerPage);
  });

}

export default paginate
db.Order.aggregate([
    { '$match'    : { "company_id" : ObjectId("54c0...") } },
    { '$sort'     : { 'order_number' : -1 } },
    { '$facet'    : {
        metadata: [ { $count: "total" }, { $addFields: { page: NumberInt(3) } } ],
        data: [ { $skip: 20 }, { $limit: 10 } ] // add projection here wish you re-shape the docs
    } }
] )
<?php 				
$servername = "";
$username = "";
$password = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $password, $dbname);

$showRecordPerPage = 10;
	if(isset($_GET['page']) && !empty($_GET['page'])){
		$currentPage = $_GET['page'];
	}else{
		$currentPage = 1;
	}
	$startFrom = ($currentPage * $showRecordPerPage) - $showRecordPerPage;
	$totalEmpSQL = "SELECT * FROM sem";
	$allEmpResult = mysqli_query($conn, $totalEmpSQL);
	$totalEmployee = mysqli_num_rows($allEmpResult);
	$lastPage = ceil($totalEmployee/$showRecordPerPage);
	$firstPage = 1;
	$nextPage = $currentPage + 1;
	$previousPage = $currentPage - 1;
	$empSQL = "SELECT * FROM `sem` WHERE is_visible = 1 ORDER BY shortby LIMIT $startFrom, $showRecordPerPage ";
	$empResult = mysqli_query($conn, $empSQL);		
 ?>

<?php
	while($emp = mysqli_fetch_assoc($empResult)){
?>

<div class="reg-box1 mb-3">
	<a href="admin/<?php echo $emp["file_link"];?>" target="_blank">
		<div class="bg-grey02 ">
			<div class="reg-download-pdf">
				<span><i class="fa fa-file-pdf-o" aria-hidden="true"></i></span> <?php echo $emp["title"];?>
			</div>
		</div>
	</a>
</div>


<?php
	}
?>

<!-- pag -->
<nav aria-label="Page navigation example mt-5">
	<ul class="pagination justify-content-center">
		<li class="page-item <?php if($currentPage <= 1){ echo 'disabled'; } ?>">
			<a class="page-link"
			href="<?php if($currentPage <= 1){ echo '#'; } else { echo "?page=" . $previousPage; } ?>">Previous</a>
		</li>
		<?php for($i = 1; $i <= $lastPage; $i++ ): ?>
		<li class="page-item <?php if($currentPage == $i) {echo 'active'; } ?>">
			<a class="page-link" href="?page=<?= $i; ?>"> <?= $i; ?> </a>
		</li>
		<?php endfor; ?>
		<li class="page-item <?php if($currentPage >= $lastPage) { echo 'disabled'; } ?>">
			<a class="page-link"
			href="<?php if($currentPage >= $lastPage){ echo '#'; } else {echo "?page=". $nextPage; } ?>">Next</a>
		</li>
	</ul>
</nav>
import { Pagination } from "antd";

const [currentPage, setCurrentPage] = useState(1);
  const [itemPerPage, setItemPerPage] = useState(25);

const indexOfLastItem = currentPage * itemPerPage;
  const indexOfFirstItem = indexOfLastItem - itemPerPage;
  const currentItem = users.slice(indexOfFirstItem, indexOfLastItem);

//IMP. NOTE {(curretitem.map)map also run by curretitem}

    <Pagination
                total={users.length}
                current={currentPage}
                pageSize={itemPerPage}
                onChange={(currentPage) => setCurrentPage(currentPage)}
              />



// place the codes in functions.php and call the function wherever you want.

function philosophy_pagination()
{
   global $wp_query;
   $links = paginate_links(array(
      'current'      => max(1, get_query_var('paged')),
      'total'        => $wp_query->max_num_pages,
      'type'         => 'list',
      'mid_size'     => 3,
   ));
   $links = str_replace('page-numbers', 'pgn__num', $links);
   $links = str_replace("<ul class='pgn__num'>", "<ul>", $links);
   $links = str_replace('next pgn__num', 'pgn__next', $links);
   $links = str_replace('prev pgn__num', 'pgn__prev', $links);
   echo wp_kses_post($links);
}
star

Tue Mar 11 2025 13:25:11 GMT+0000 (Coordinated Universal Time)

#ajax #blog #pagination
star

Tue Mar 11 2025 13:23:39 GMT+0000 (Coordinated Universal Time)

#ajax #blog #pagination
star

Tue Mar 11 2025 13:22:43 GMT+0000 (Coordinated Universal Time)

#ajax #blog #pagination
star

Mon Aug 28 2023 21:14:16 GMT+0000 (Coordinated Universal Time)

#javascript #pagination #array #of #arrays
star

Thu Feb 16 2023 05:30:40 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/48305624/how-to-use-mongodb-aggregation-for-pagination

#aggregation #mongodb #pagination
star

Sat Jan 21 2023 07:23:21 GMT+0000 (Coordinated Universal Time) https://codingstatus.com/how-to-create-pagination-in-php-mysql/

#pagination #corephp
star

Thu Oct 27 2022 12:40:10 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=kM73pwJpT1M

#react #antd #pagination
star

Tue May 31 2022 14:49:26 GMT+0000 (Coordinated Universal Time) https://wordpress.stackexchange.com/questions/53194/wordpress-paginate-wpdb-get-results

#wordpress #wpdb #pagination #php
star

Sat May 14 2022 10:38:29 GMT+0000 (Coordinated Universal Time)

#pagination #function

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension