LatentDenis
LatentDenis

Reputation: 2991

WordPress: How to output Post images by category?

I'm trying to loop through all categories one by one, and printing out the post title/image/image-link. How can I make my code work?

<?php $categories= get_categories();
        foreach ($categories as $cat) {
            echo '<div>'.
            $posts = get_posts(array('category' => $cat->term_id));
            if ($posts) {
                foreach ($posts as $p) {
                    echo get_the_post_title( $p->title ).'<br>';
                    echo get_the_post_thumbnail( $p->ID, 'medium' ).'<br>';
                    echo get_the_post_thumbnail_link( $p->imagelink, 'medium' ).'<br>';
                }
            }
        }
?>

I know my echo statements are probably wrong in the second foreach loop, but it's absolutely important the first for loops stays the same/where it is. Please help.

Upvotes: 0

Views: 269

Answers (1)

Emil
Emil

Reputation: 1816

So...

  1. Typo in line 3.
  2. get_the_post_thumbnail() is not a function, use get_the_title().
  3. get_the_post_thumbnail_link() is not a function (if not defined by you ofc), use wp_get_attachment_image_src().

Try this:

<?php $categories= get_categories();
        foreach ($categories as $cat) {
            echo '<div>';
            $posts = get_posts(array('category' => $cat->term_id));
            if ($posts) {
                foreach ($posts as $p) {
                    echo get_the_title( $p->ID ).'<br>';
                    echo get_the_post_thumbnail( $p->ID, 'medium' ).'<br>';
                    echo wp_get_attachment_image_src( get_post_thumbnail_id($p->ID), 'medium' )[0];

                }
            }
        }
?>

Upvotes: 1

Related Questions