• Resolved Archidibus

    (@archidibus)


    Hi Community,
    I’m having an issue with a little code. Under each article on my page should appear my “recent posts” and below the tags of my post and some share buttons. Unfortunately, the data relate to the last “recent post” not to the article itself.
    Does anyone have a solution?

    <?php
    /* Recent Posts */
    if (is_single()) {
    $post_ID = $wp_query->posts[0]->ID;
    $all_cats_of_post = get_the_category($post_ID);
    $first_cat_ID = $all_cats_of_post[0]->cat_ID;
    $first_cat_name = $all_cats_of_post[0]->cat_name;
    ?>
        <div class="related-posts"><h3>Verwandte Artikel:</h3>
            <ul>
            <?php global $post; $cat_posts = get_posts('numberposts=3&category='.$first_cat_ID);
            foreach($cat_posts as $post) : ?>
                <li><i class="fa fa-caret-right"></i>
     <?php echo wp_get_attachment_image( $attachment->ID, 'full' );?><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
            <?php endforeach; ?>
            </ul>
        </div>
    <?php } ?>
    
    <?php
    /* Tags */
    the_tags( '<div class="entry-meta"><span class="tag-links">', '', '</span></div>' ); ?>

    Example PostPictorialization

Viewing 2 replies - 1 through 2 (of 2 total)
  • WordPress uses the $post variable in the loop, and will use that in your the_tags() function. You’re overriding $post in your foreach loop; so, the_tags() is using the last post in your foreach loop as the $post to pull tags for.

    Two solutions for you.

    #1: Assign the $post variable to a temporary one, and then reset it after your foreach loop:

    <?php
      global $post;
      $temp = $post;
      $cat_posts = ...
      foreach( $cat_post as $post ): ?>
        //Your foreach loop
      <?php
      endforeach;
      $post = $temp;
      the_tags(...);
    ?>

    #2: Alternatively (and perhaps better), don’t use $post in your foreach:

    <?php foreach( $cat_post as $article ):?>
      <li><i class="fa fa-caret-right"></i>...
        <a href="<?php print get_permalink( $article->ID ); ?>">
          <?php print get_the_title( $article->ID ); ?>
        </a>
      </li>
    <?php endforeach; ?>
    Thread Starter Archidibus

    (@archidibus)

    It works perfectly now. Thanks so much.
    The issue has been resolved ??

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Incorrect reference’ is closed to new replies.