• Rose

    (@eos-rose)


    I have custom field relatedPosts with a list of comma-separated numerical values of post ids (example: 417, 1047, 1243). I would like to somehow run a loop that will pull the title and permalink for each of these post ids to display as a list in my post template (single.php). Ideally, these posts would be ordered descending based on the date modified, but that’s less important.

    I’m not fooling myself into thinking this is possible, am I?

Viewing 1 replies (of 1 total)
  • vtxyzzy

    (@vtxyzzy)

    It is possible. Here is one solution:

    Add this function to your functions.php or in your custom single.php template:

    <?php function show_related_posts() {
    
       global $post;
       $meta_value = get_post_meta($post->ID, 'relatedPosts', true);
       $related = explode( ',', $meta_value );
       $args = array(
          'post__in' => $related,
          'ignore_sticky_posts' => 1,
       );
       $related_posts = new WP_Query( $args );
       if ( $related_posts->have_posts() ) :
          echo '<ul>';
          while ( $related_posts->have_posts() ) :
             $related_posts->the_post();
             ?>
             <li><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></li>
             <?php
          endwhile;
          echo '</ul>';
       endif;
    }
    
    ?>

    And add a call to the function inside your loop, something like this:

    if (have_posts()) {
       while (have_posts()) {
          the_post();
          echo '<h2>'; the_title(); echo '</h2>';
          the_content();
          show_related_posts();
       }
    }
Viewing 1 replies (of 1 total)
  • The topic ‘Loop custom field with list of related post ids’ is closed to new replies.