最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Get image of latest post from taxonomiescategories

programmeradmin2浏览0评论

I have a custom post type "Artworks" with a custom taxonomy "Artists". I have a page where I list all the entries from the "Artists" taxonomy (Artist 1, Artist 2, Artist 3, etc.).

How can I get the picture from the latest post in each category (Artist 1, Artist 2, etc.)?

That's how I list the entries from the "Artists" taxonomy:

<style>
    .artistbox {
        width:100%;
        height:150px;
    }
</style>

<?php
    $tax_terms = get_terms('artists', array('hide_empty' => '1'));      
        foreach ( $tax_terms as $tax_term ):  
            echo '<div class="artistbox"  style="background-image: url('?????????');"><a href="/artists/'.$tax_term->slug.'">'.$tax_term->name.'</a></div>';  
        endforeach;
?>

I want ????????? to be URL of the featured image of the latest post from each category. How can I do that?

Like this:

    <div style="background-image:URL('featured-image-of-latest-post-assigned-to-artist-1;">
    Artist 1
    </div>


    <div style="background-image:URL('featured-image-of-latest-post-assigned-to-artist-2;">
    Artist 2
    </div>

    <div style="background-image:URL('featured-image-of-latest-post-assigned-to-artist-3;">
    Artist 3
    </div>

... and so on.

I have a custom post type "Artworks" with a custom taxonomy "Artists". I have a page where I list all the entries from the "Artists" taxonomy (Artist 1, Artist 2, Artist 3, etc.).

How can I get the picture from the latest post in each category (Artist 1, Artist 2, etc.)?

That's how I list the entries from the "Artists" taxonomy:

<style>
    .artistbox {
        width:100%;
        height:150px;
    }
</style>

<?php
    $tax_terms = get_terms('artists', array('hide_empty' => '1'));      
        foreach ( $tax_terms as $tax_term ):  
            echo '<div class="artistbox"  style="background-image: url('?????????');"><a href="/artists/'.$tax_term->slug.'">'.$tax_term->name.'</a></div>';  
        endforeach;
?>

I want ????????? to be URL of the featured image of the latest post from each category. How can I do that?

Like this:

    <div style="background-image:URL('featured-image-of-latest-post-assigned-to-artist-1;">
    Artist 1
    </div>


    <div style="background-image:URL('featured-image-of-latest-post-assigned-to-artist-2;">
    Artist 2
    </div>

    <div style="background-image:URL('featured-image-of-latest-post-assigned-to-artist-3;">
    Artist 3
    </div>

... and so on.
Share Improve this question edited Apr 7, 2020 at 14:48 HAL2020 asked Apr 7, 2020 at 12:51 HAL2020HAL2020 398 bronze badges 3
  • Welcome to WordPress Development. I hope you find the answer(s) you are looking for. Our site is different from most - if you have not done so yet, consider checking out the tour and help center to find out how things work. – Matthew Brown aka Lord Matt Commented Apr 7, 2020 at 12:59
  • Give more details on your code. Like what $latestimage variable pull ? – Maidul Commented Apr 7, 2020 at 13:31
  • @Maidul Maybe Sorry if I wasn't clear with my question (I'm not a developer). I use a custom post type "Artwork" with a custom field "Artist", which is saved as a custom taxonomy "Artists". Domain/artworks leads to an archive page of all "artwork" custom posts. Every post has an Artist assigned to it. Domain/artists leads to a custom page that lists all Names from my "Artists" taxonomy: <div>Artist Name 1</div><div>Artist 2</div> etc. Now I want these DIVs to have individual background images. Artist 1 DIV should have the image of the latest post that is assigned to Artist 1, and so on. – HAL2020 Commented Apr 7, 2020 at 14:36
Add a comment  | 

1 Answer 1

Reset to default 0

There's not a real efficient way to do this. You'll either have to make 3 queries or create your own SQL query and use global $wpdb;. For simplicity purposes I've went with a 3 query approach.

If we know the slugs or IDs we can pass them to our tax query. Since the example code does not show that we need to run get_terms() first to get the possible artists:

$artists = get_terms( array( 'taxonomy' => 'artist', 'hide_empty' => false, ) );

We can use get_posts() to grab an Array of posts of a specific artist like so:

$art1_posts = get_posts( array(
    'posts_per_page'    => 1,       // Only return 1 post
    'orderby'           => array(   // Order by Date
        'post_date' => DESC
    ),
    'tax_query'         => array( array(    // Get first artist posts - inefficient
        'taxonomy'  => 'artists',
        'field'     => 'term_id',
        'terms'     => $artists[0]->term_id
    ) ),
    'meta_key'          => '_thumbnail_id', // Only return posts that have a post thumbnail
) );

The above is only an example since it's using $artists[0]. We instead want to loop through the available artists and store the results in a separate array. The final result could look something like this:

$featured_image_arr = array();

$artists = get_terms( array(
    'taxonomy'   => 'artist',
    'hide_empty' => false,
) );

// If we have artists, loop through them, get the latest post, add to our featured image arr
if( ! empty( $artists ) ) {

    foreach( $artists as $artist ) {

        $artist_posts = get_posts( array(
            'posts_per_page'    => 1,
            'orderby'           => array(
                'post_date' => DESC
            ),
            'tax_query'         => array( array(
                'taxonomy'  => 'artists',
                'field'     => 'term_id',
                'terms'     => $artist->term_id
            ) ),
            'meta_key'          => '_thumbnail_id',
        ) );

        // Skip empty artists.
        if( empty( $artist_posts ) ) {
            continue;
        }

        $featured_image_arr[] = array(
            'artist'      => $artist,
            'artist_post' => $artist_posts[0],
            'thumbnail_id'=> get_post_meta( $artist_posts[0]->ID, '_thumbnail_id', true ),
            'thumbnail_url'=> wp_get_attachment_image_url( $thumbnail_id, 'full' ),
        );

    }

}

// If we have featured images, show them.
if( ! empty( $featured_image_arr ) ) {

    foreach( $featured_image_arr as $arr ) {

        printf( '<div class="artistbox" style="background-image: url( %1$s )"><a href="/artists/%2$s">%3$s</a></div>',
            $arr['thumbnail_url'],
            $arr['artist']->slug,
            $arr['artist']->name
        );

    }

}
发布评论

评论列表(0)

  1. 暂无评论