'?php the_permalink() returns wrong post ID and 404 error

I'm having an issue with grabbing the correct post ID using the_permalink() -- see code below:

<?php
  while( $wpr->have_posts() ) :
    $wpr->the_post();
    ?>
      <?php $wpcover = get_field('whitepaper_cover'); ?>
    <li>
    <a href="<?php the_permalink(); ?>?rel=wp-related"><img src="<?php echo $wpcover['url']; ?>" alt="<?php echo $wpcover['alt']; ?>" /></a>
    <a href="<?php the_permalink(); ?>?rel=wp-related"><?php the_title(); ?></a>
    <a href="<?php the_permalink(); ?>?rel=wp-related" class="btn-2">Get it Now</a>
    </li>
      
    <?php
  endwhile;
  wp_reset_postdata();
?>`

For example, on one page the_permalink() is grabbing the post ID link as p=17005 (a post that doesn't exist) when it SHOULD be p=28649, leading to a 404 error. Any ideas?

I tried resetting permalinks and updating elementor plugins, neither of which worked. Also tried various suggetions from browsing stackexchange but none really matched this exact issue. The code looks good to me, but maybe I'm missing something?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source