Wordpress get featured image URL from category

2019-08-15 02:20发布

I found a simple code that gets the featured image from a post.

<?php
        $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 1680,470 ), false, '' );
         echo $src[0];  
?>

I need this for a page that uses a image from a category "slider" and sets featured image. This will make a header image on the page.

<?php
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 1680,470 ), false, '' );

?>


<div id="header-hero" style="background-image: url('<?php echo $src[0]; ?>');">

But if someone makes a new post in another category it fails. So, how can I get the image from the category? It will be only one image in the category so it makes it a little easier. Hope for some wordpress-gurus :)

标签: php wordpress
2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-15 02:57

Use WP_query, with parameters in array.

$args = array(
    'category_name'=>'your-category-slug',
    'posts_per_page'=> 10,
);
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
    //Post data
    echo get_the_post_thumbnail(get_the_ID());
endwhile;
查看更多
Deceive 欺骗
3楼-- · 2019-08-15 02:59

Try this:

<?php 
$slider_category_id = 123213;
query_posts('showposts=1&cat='.$slider_category_id);
if (have_posts()) : while (have_posts()) : the_post(); 
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 1680,470 ), false, '' );
?>
<div id="header-hero" style="background-image: url('<?php echo $src[0]; ?>');">
<?php endwhile; endif; ?>
<?php wp_reset_query(); ?>
查看更多
登录 后发表回答