WordPress.org

Ready to get started?Download WordPress

Forums

Display post thumbnail inside of php output (6 posts)

  1. JohnPro992
    Member
    Posted 3 years ago #

    I am very basic when it comes to php and I wanted to modify the php code below to display the post image before the permalink.

    The original code below of the plugin:

    function posts_list () {
    	$output= '<ul>';
    	$posts = get_posts('numberposts=-1');
    	foreach($posts as $post){
    		$permalink = get_permalink( $post->ID );
    		$output.= '<li>' . '<a href="' . $permalink . '">' . $post->post_title . '</a></li>';
    	}
    	$output.='</ul>';
    	return $output;
    }

    Then i tried the following:

    [Code moderated as per the Forum Rules. Please use the pastebin]

    lol your probably laughing at my attempts but how do I separate them for it to work? I tried adding . and quotes nothing worked. I get a fatal error plugind disabled.

  2. gerbilk
    Member
    Posted 3 years ago #

    add the_post_thumbnail( 'thumbnail' ); after the { and before $permalink = ...

  3. JohnPro992
    Member
    Posted 3 years ago #

    Thanks gerbik, it didnt show errors but it created numerous images of the same post image. Not the featured images of the permalinks. perhaps its more complex than I thought.

  4. Mark / t31os
    Moderator
    Posted 3 years ago #

    You need to use get_the_post_thumbnail with your function to get a return value instead of a printed one, here's a tweaked version of your function.

    function posts_list () {
    
    	$output = '';
    	$posts = get_posts( 'numberposts=-1' );
    
    	foreach( $posts as $post )
    		$output .= '<li>' . get_the_post_thumbnail( $post->ID ) . '<a href="' . get_permalink( $post->ID ) . '">' . $post->post_title . '</a></li>';
    
    	$output = '<ul>' . $output . '</ul>';
    
    	return $output;
    }
  5. JohnPro992
    Member
    Posted 3 years ago #

    wow thats awesome Mark! It worked great! This looks like fun, the possibilities with coding. :D

    Appreciate it!

  6. Mark / t31os
    Moderator
    Posted 3 years ago #

    You're welcome. :)

Topic Closed

This topic has been closed to new replies.

About this Topic