Viewing 2 reply threads
  • Author
    Posts
    • #5583
      pwwwpwww
      Member

      The docs are great if you know PHP, if not they may as well be written in moon-speak. I struggled to get the relate field to print out a nice list of links in my theme. The example in the docs just prints out the post titles – no urls / permalinks. Here’s how I managed to do it.

      First, create your field-

      <?php
      /*
      Title: Add links to other useful posts
      Post Type: post
      */
      
      piklist('field', array(
      'type' => 'post-relate'
      ,'scope' => 'post'
      ,'template' => 'field'
      ));

      Next, go ahead and create a test post and add some related posts to your new field.

      Now open up the theme file that displays your single posts (single.php). You’ll find some moon-speak similar to the following:

      <?php
      // Start the loop.
      while ( have_posts() ) : the_post();
      
      // Some more moon-speak that prints out the post - removed for brevity. 
      			
      // End of the loop.
      endwhile; ?>

      Before the end of your post loop, add the following:

      <?php         
      $related = get_posts(array(
      'post_type' => 'posts' // Set post type you are relating to.
      ,'posts_per_page' => -1
      ,'post_belongs' => $post->ID
      ,'post_status' => 'publish'
      ,'suppress_filters' => false // This must be set to false
      ));
      ?>
      
      <ul>
      <?php foreach($related as $related_post) {
      echo '<li><a href="'.get_post_permalink($related_post->ID).'">'.$related_post->post_title.'</a></li>';
      } ?>
      </ul>

      Viola! A nice list of links to your related posts. Please note this doesn’t work outside of the main post loop. So no trying to stick it in your sidebar. If anyone knows how to get this to work outside of the loop, I’d love to know!

    • #5590
      Steve
      Keymaster

      The best part of Piklist is that you can use standard WordPress functions to access your data… which also means that any standard WordPress tutorial will also work for you.

      Here’s a good tutorial on a few ways to display Post Content. The last three will work for you.

    • #5627
      pwwwpwww
      Member

      Thanks for the reply Steve. As it turns out, the code I used above works just fine in the sidebar – no WP_Query or other wizardry needed. Not sure why it wouldn’t work the first 6 times I tried 🙂

Viewing 2 reply threads
  • The topic ‘Post to Post Relationships – Displaying a list of related posts in your theme’ is closed to new replies.