2

I have this code below, and I wish to show each link of each post, but I keep getting same link to all posts which is the link of the page.

$args = array('posts_per_page' => 5,'order' => 'DESC');
$rp = new WP_Query($args);
if($rp->have_posts()) :
while($rp->have_posts()) : $rp->the_post();

   the_title(); 

$link=the_permalink();
echo '<a href="'.$link.'">Welcome</a>';
echo "<br />";

endwhile;

wp_reset_postdata(); 

endif;

Thank you.

  • This might not solve your problem, but i wonder why you are storing your permalinks in a variable. You can use it directly. – Jack Johansson Apr 7 '17 at 12:21
2

Don't forget to use esc_url()

echo '<a href="'. esc_url( $link ).'">Welcome</a>';

Also try this: get_permalink( get_the_ID() );

  • the esc_url() didn't help, I get same result. The second command just works fine :) , thank you – eawedat Apr 7 '17 at 11:16
  • It's important to use escaping functions such as esc_url, esc_html, esc_attr for safety reasons. :) This url might be helpful to you: WordPress Escape Functions – kiarashi Apr 7 '17 at 11:18
  • could you tell please, why when using the_permalink(); alone without echo or anything else, it would work while when using it as a link or href as above it does not work? – eawedat Apr 7 '17 at 11:23
  • Maybe this website could clear things up for you: get_permalink WP Codex – kiarashi Apr 7 '17 at 11:34
1
$args = array('posts_per_page' => 5, 'order' => 'DESC');
$rp   = new WP_Query($args);
if ($rp->have_posts()) :
    $i    = 0;
    $link = '';
    while ($rp->have_posts()) : $rp->the_post();
        the_title();
        if ($i == 0) $link = get_permalink();

        echo '<a href="' . $link . '">Welcome</a>';
        echo "<br />";
        $i++;
    endwhile;

    wp_reset_postdata();

endif;

this core get only first post link

0

You are missing get_the_ID() inside the loop. Thats why its showing the permalink of first post for each post inside the loop;

Try this code

$args = array('posts_per_page' => 5,'order' => 'DESC');
$rp = new WP_Query($args);
if($rp->have_posts()) :
while($rp->have_posts()) : $rp->the_post();

   the_title(); 

$link=get_the_permalink(get_the_ID()); //get_the_ID() gets the id of the post inside a loop
echo '<a href="'.$link.'">Welcome</a>';
echo "<br />";

endwhile;

wp_reset_postdata(); 

endif;

Note: Please check the documentation for better understanding.

  • the thing is when using the_permalink(); without any addition like echo before it, it works :\ – eawedat Apr 7 '17 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.