• Hi I want to achieve something very spoecific. I should say that I have tried the plugins listed on this site, but haven’t found anyone/or I have not been god enough to modify it so that it would do this.

    Under each post in my single.php I would like to show 2 random posts from the tags associated with the post, together with an image from a custom field plus the Excerpt.

    So under each post, I would like to get two random posts from the tags returned by:

    <?php
    $posttags = get_the_tags();
    if ($posttags) {
    foreach($posttags as $tag) {
    echo $tag->name . ' ';
    }
    }
    ?>

    And show them like this:

    <div class="related_posts">
      <h2>Related posts</h2>
      <div class="first_related"> <a href="<?php the_permalink(); ?>"><img src="customfield_image" /></a>
        <p><a href="<?php the_permalink(); ?>">
          <?php the_title(); ?>
          </a></p>
        <p>
          <?php the_excerpt(); ?>
        </p>
      </div>
      <div class="second_related"> <a href="<?php the_permalink(); ?>"><img src="customfield_image" /></a>
        <p><a href="<?php the_permalink(); ?>">
          <?php the_title(); ?>
          </a></p>
        <p>
          <?php the_excerpt(); ?>
        </p>
      </div>
    </div>

    I have also tried to have a look at the “Custom Post Listing” plugin but I couldn’t see if it would be able to do this.

    Hopefully someone can give me some leads to follow.

Viewing 15 replies - 1 through 15 (of 18 total)
  • Can you clarify this part:

    I would like to get two random posts from the tags returned by…”

    You want to select posts with *all* related tags, or any (er, random) tag from the list, or what?

    Thread Starter kasperbs

    (@kasperbs)

    the following piece of code:

    <?php
    $posttags = get_the_tags();
    if ($posttags) {
    foreach($posttags as $tag) {
    echo $tag->name . ' ';
    }
    }
    ?>

    return the tags related to a post, lets say for this example it returned the following: wordpress “racing cars” cereal

    Now i want to gather all posts that have one or more of these tags associated with them. From those posts I want to select two random posts and show them like above with the excerpt and and image from a custom field.

    Hope it clarifies. I know it’s very specific but it’s not uncommon to see related posts shown with an image and a summary. Check the very bottom of this page, that is very similar to what I would like to do:
    http://globalflyfisher.com/patterns/pinkpig/

    Based on what you pointed to above, I went a little crazy on your request:

    http://wordpress.pastebin.ca/869461

    Note the custom database query in the code linked above primarily evaluates on two things when selecting posts: one or more tags from the current post, and the existence of the custom field key. This way it should always collect (randomly ordered) only those posts which provide both.

    The $limit and $custom_key vars at the start of the code statement are user-configurable.

    Also, I didn’t insert the HTML from your example above, but hopefully I’ve *modularized* the code enough so it’s obvious where to add HTML or make layout changes. Let me know if there’s anything else in need of explaining.

    Thread Starter kasperbs

    (@kasperbs)

    Thanks man!
    It seems to work perfectly, I’m not finished implementing it yet, but unless I comment out the last
    rewind_posts();
    It won’t work.
    Basically if I don’t do it, the single post that is displaying keeps coming over and over again repeating itself forever.

    I have had this problem before when trying to implement code I’ve got from the net. Could you please explain why that happens, and if I need that rewind_posts(); in there at all?

    Thanks

    Could you please explain why that happens, and if I need that rewind_posts(); in there at all?

    Sounds like you’re implementing it within the preceding post loop, which would (naturally) reset the loop before it ends.

    I included it in my code because on the setup I test with the custom loop for displaying the related posts was affecting something else downstream (part of the current post object). If you don’t see any problems it can certainly be excluded. To be safe I’d recommend inserting it on its own right after the post loop in your template ends.

    Thread Starter kasperbs

    (@kasperbs)

    Cheers mate, it makes sense. It doesn’t affect anything at all, your code works perfect without it. Thanks you very much again I appreciate you taking the time to help me, quality support you have given me with this issue.

    Thread Starter kasperbs

    (@kasperbs)

    Ok I might have been too fast here. There seems to be problem with the commenting after I have implemented this. When I make a comment it appears on a completely different post. The code below is my template. (it works if I take out the code inside the related_items div:

    <?php the_content() ?>
            <div class="related_items">
              <?php
          $limit = 3; // # of posts to display
          $art_img_teaser = 'art_img_teaser'; // custom field key for image url
    
          $posttags = get_the_tags();
    
          if ($posttags) {
    
                  foreach($posttags as $tag) {
                          $sep = ( $tags ) ? ',' : '';
                          $tags .= $sep . '\'' . $tag->name . '\'';
                  }
          }
    
          $rand_tag_posts = $wpdb->get_results("SELECT $wpdb->posts.* FROM $wpdb->posts INNER JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) INNER JOIN $wpdb->terms ON ($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id) WHERE $wpdb->term_taxonomy.taxonomy = 'post_tag' AND $wpdb->terms.name IN ($tags) AND $wpdb->postmeta.meta_key = '$art_img_teaser' AND post_type = 'post' AND (post_status = 'publish') AND $wpdb->posts.ID <> $post->ID GROUP BY $wpdb->posts.ID ORDER BY RAND() LIMIT $limit");
    
          if( $rand_tag_posts ) : foreach( $rand_tag_posts as $post ) : setup_postdata($post);
    
    	   // Variables to collect from the retrieved posts
          $art_img_teaser_url = get_post_meta($post->ID, $art_img_teaser, true);
    	  $rel_excerpt = $post->post_excerpt;
    	   // collect the $art_img_teaser value
    
          ?>
              <div class="related_post"> <a href="<?php the_permalink(); ?>"><img src="<?php bloginfo(url); echo $kasper_image_path .'teasers/thumb_'; ?><?php echo $art_img_teaser_url; ?>" alt="<?php the_title_attribute(); ?>" title="<?php the_title_attribute(); ?>" /></a> <a href="<?php the_permalink(); ?>">
                <h3>
                  <?php the_title(); ?>
                </h3>
                <?php if ( $post->post_excerpt ) : // If there is an explicitly defined excerpt ?>
                <?php
    			$sentences = preg_split('/\./', $rel_excerpt, -1 , PREG_SPLIT_NO_EMPTY);
    			echo '<p>' . $sentences[0] . '</p>';
    		  ?>
                <?php else : ?>
                <?php wswwpx_content_extract ($more_link_text = 'More', $test_len=85, $cut_len='1:s', $addtodb=false, $beforehtml='<p>', $afterhtml='</p>', $strip_tags=true, $with_more_link=false); ?>
                <?php endif;  ?>
                </a> </div>
              <?php endforeach; endif; //rewind_posts(); ?>
            </div>
          </div>
          <div class="post_meta2"> </div>
          <?php endwhile; ?>
          <?php else : ?>
          <p>Sorry, but you are looking for something that isn't here, try searching for it.</p>
          <?php include (TEMPLATEPATH . "/searchform.php"); ?>
          <?php endif; ?>
        </div>
      </div>
    </div>
    </div>
    <div id="sub_wrapper">
      <?php comments_template(); ?>
      <div class="clear"></div>
    </div>
    <?php get_footer(); ?>

    Try adding rewind_posts() just before the commments template is loaded, and see if that resolves it:

    <div id="sub_wrapper">
    <?php rewind_posts(); ?>
    <?php comments_template(); ?>
    <div class="clear"></div>

    Thread Starter kasperbs

    (@kasperbs)

    No, the comment still show up on some other post. What happens is, as soon as a press submit comment, I’m taken to another post where my comment shows up.

    EDIT:
    It seems that the problem only exists on certain posts. I’m not sure what it is but on some posts there is no problem. I will keep trying to figure out if there is some kind of pattern.

    UPDATE:
    OK I have now made a few dozens of comments, and the problem is on every post where there are related posts, whether or not the rewind_post() is shown or commented out.

    I looked into this and it seems (at least in this case) running rewind_posts() is not quite enough. Instead use:

    <?php rewind_posts(); the_post(); ?>

    That should reset the ID (and everything else) to that of the current post for comments and whatnot.

    Thread Starter kasperbs

    (@kasperbs)

    Thanks, by placing this just before the comment template, it seems to work perfectly. Thanks again for you fast and accurate support.

    Hey Kafkaesqui, This some really good code. In fact, I have been trying to modify several plugins (like YARPP) for about 50 hours now and this is the perfect solution.

    The only problem is that I really don’t want it to be limited by the existence of the custom field key. I am using the Post Thumbs plugin, which is perfect for getting the image to display, so the custom field would just add to much complication to adding a new post.

    Okay, so I think the problem I’m having is in this bit of code:

    $rand_tag_posts = $wpdb->get_results("SELECT $wpdb->posts.*
    FROM $wpdb->posts
    INNER JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id)
    INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    INNER JOIN $wpdb->terms ON ($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
    WHERE $wpdb->term_taxonomy.taxonomy = 'post_tag'
    AND $wpdb->terms.name IN ($tags)
    AND $wpdb->postmeta.meta_key = 'img'
    AND post_type = 'post'
    AND (post_status = 'publish')
    AND $wpdb->posts.ID <> $post->ID GROUP BY $wpdb->posts.ID
    ORDER BY RAND() LIMIT $limit");

    With a lot of trial and error, I actually got my posts to display when I cut it down to the following:

    $rand_tag_posts = $wpdb->get_results("SELECT $wpdb->posts.*
    FROM $wpdb->posts
    INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    INNER JOIN $wpdb->terms ON ($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
    WHERE $wpdb->term_taxonomy.taxonomy = 'post_tag'
    AND post_type = 'post'
    AND (post_status = 'publish')
    AND $wpdb->posts.ID <> $post->ID GROUP BY $wpdb->posts.ID
    ORDER BY RAND() LIMIT $limit");

    But now it doesn’t pull related tags. It just randomly shows two posts regardless of what the tags say.

    I would really appreciate any help you could offer, as I have literally been pulling my hair out on this one.

    Thanks a Million Kafkaesqui, that fixed my problem as well. Seems like any loops run inside single.php would need that bit of code. Don’t mind me adding in search phrases below.

    comments broken on single post. Comments on wrong post. Custom loop single.php. Comments broken loop. new wp_query(). query_posts(). template.

    🙂

    Kafkaesqui could you post the code again. The link you provided no longer works. Thank you.

    hi

    Kafkaesqui, sorry this is into php now but I’m just curious, I know what’s happening in the two lines below (tag names added in single quotes, seperated by commas) but how does it not add the last (unnecessary) comma? It’s that “? :” which is an operator or control structure right?

    $sep = ($tags) ? ‘,’ : ”;
    $tags .= $sep.’\”.$tag->name.’\”;

    usually I’d do:

    tags = substr(tags, 0, strrpos(tags, ‘,’));

    right after my foreach but yours is much more elegant.

    a+
    gar

Viewing 15 replies - 1 through 15 (of 18 total)
  • The topic ‘Show related posts with excerpt and key/value’ is closed to new replies.