0

I wanna create an archive page for both normal posts and a custom post type(gallery). I created an index.php file and put my code in there but its pagination ain't work correctly. all pages look the same! Is there any way to fix it?

Here is my code:

<?php
$allPosts = new WP_Query(array(
    'post_type' => array('post', 'gallery'),
    'posts_per_page' => 12
));

while ($allPosts->have_posts()) {
    $allPosts->the_post();
    $thumbnail_id = get_post_thumbnail_id();
    $thumbnail_url = get_the_post_thumbnail_url();
    $alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
?>

    <div class="gallery-container">
      <div class="inner-gallery-container">
      <img alt="<?php echo $alt ?>" class="gallery-image" src="<?php echo $thumbnail_url ?>">

            <div class="image-date">
                <span>
                    <?php the_time('F j,Y'); ?>
                </span>
            </div>

            <h4 class="gallery-title">
                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            </h4>
        </div>
    </div>

<?php }
wp_reset_postdata();
?>
3
  • 1
    pagination doesn't work because new WP_Query doesn't change the posts that get displayed, it's a brand new query that fetches brand new posts. Now you have 2 queries, the main query and your new query, and the pagination is only going to work for the main query. There are fixes but it's much much easier to modify the original query and avoid paying the 2x slow down using pre_get_posts to tell WP you want to have galleries and posts
    – Tom J Nowell
    Sep 13 at 14:38
  • 1
    likewise, index.php is the default fallback template, not the homepage/archive template, take a look at the template hierarchy. Note that the approach you took is fundamentally incompatible with block themes too
    – Tom J Nowell
    Sep 13 at 14:38
  • @TomJNowell thanks for your comment, I'd so thankful if u can gimme a code example for that.🙏 Sep 16 at 17:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.