php wordpress get post by id and make featured section on every page

I just recently code a featured section that will actually pull the post where it specify in the array. Here is the code

<div class="container_24">
<ul id="featured_posts" class="grid_24">

<?php $thePostIdArray = array("13968","14293", "15018", "15512"); ?>
<?php $limit = 4 ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); $counter++; ?>
<?php if ( $counter < $limit + 1 ): ?>

<?php $post_id = $thePostIdArray[$counter-1]; ?>
<?php $queried_post = get_post($post_id); ?>
 <li class="featured_post">
    <div class="featured_thumbnail"> <a href="<?php echo get_permalink( $post_id ); ?>"><img width="55" height="55" src="<?php echo img_feature($post_id) ?>" class="attachment-featured-small wp-post-image" alt="<?php echo $queried_post->post_title; ?>"></a></div>
    <div class="featured_title">
      <h2><a href="<?php echo get_permalink( $post_id ); ?>"><?php echo $queried_post->post_title; ?></a></h2>
    </div>
  </li>

<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>

</ul>
</div>

Now this code working perfectly on home, archive and any page that have loop of post and it shows 4 featured post as it suppose to, but the problem it doesn’t show on any other pages that doesn’t have loop of post like single.php or contact page and any other that is like a single page with no post.

Read More

I don’t know if I did anything wrong above I have include this on the header which suppose to display to all the pages that include header and the problem is only show the first one and not the rest is like the loop only go once and stop.

Please point me out if I did anything wrong.

Thanks

Related posts

Leave a Reply

1 comment

  1. Use a foreach loop like below.

    <div class="container_24">
    <ul id="featured_posts" class="grid_24">
    
    <?php $thePostIdArray = array("13968","14293", "15018", "15512"); ?>
    <?php foreach ($thePostIdArray as $post_id) : ?>
        <?php $queried_post = get_post($post_id); ?>
         <li class="featured_post">
            <div class="featured_thumbnail"> <a href="<?php echo get_permalink( $post_id ); ?>"><img width="55" height="55" src="<?php echo img_feature($post_id) ?>" class="attachment-featured-small wp-post-image" alt="<?php echo $queried_post->post_title; ?>"></a></div>
        <div class="featured_title">
            <h2><a href="<?php echo get_permalink( $post_id ); ?>"><?php echo $queried_post->post_title; ?></a></h2>
        </div>
      </li>
     <?php endforeach; ?>
    
    </ul>
    </div>