WordPress.org

Ready to get started?Download WordPress

Forums

Getting A Custom Link on a Featured Image (4 posts)

  1. Balanced Design
    Member
    Posted 1 year ago #

    $query = new WP_Query(array('cat' => 3, 'posts_per_page' => 20, 'meta_key' => '_thumbnail_id'));
    	while($query->have_posts()) :
        $query->the_post();
        the_post_thumbnail();
    	endwhile;

    Above you will find the code I used on a custom template page to output the thumbnails to specific posts. That's first thing! It works like a charm. Now, I need to add the hyperlink on the image so that when the featured image is clicked, it will take my user back to the actual post. How do I do this?

  2. bythegram
    Member
    Posted 1 year ago #

  3. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

    http://codex.wordpress.org/Function_Reference/the_permalink
    http://www.w3schools.com/html/html_links.asp

    example:

    $query = new WP_Query(array('cat' => 3, 'posts_per_page' => 20, 'meta_key' => '_thumbnail_id'));
    	while($query->have_posts()) :
        $query->the_post();
        echo '<a href="'; the_permalink(); echo '">';
        the_post_thumbnail();
        echo '</a>';
    	endwhile;

    or more complex, so you don't end up with an empty link html tag if there is no thumbnail:

    $query = new WP_Query(array('cat' => 3, 'posts_per_page' => 20, 'meta_key' => '_thumbnail_id'));
    	while($query->have_posts()) :
        $query->the_post();
        if( has_post_thumbnail() ) {
          echo '<a href="'; the_permalink(); echo '">';
          the_post_thumbnail();
          echo '</a>';
        }
    	endwhile;

    don't forget to add wp_reset_postdata(); after the endwhile;

  4. Balanced Design
    Member
    Posted 1 year ago #

    @alchymyth That worked perfectly. Thanks!

    Now on to styling it with CSS.

Topic Closed

This topic has been closed to new replies.

About this Topic