skip to Main Content

I want to display the featured image outside of the WP-loop. e. g. like a background image of the body that is different in every post. I looked for two hours on google, but could not find a single piece of code that gives me an idea. But I suppose it is not that much complicated.

Has anybody here an idea how the retrieve the URL of the featured image outside the loop?

thank"

2

Answers


  1. Try This:

    <?php
      global $post;
      if (has_post_thumbnail($post->ID)) {
        $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'single-post-thumbnail');
      }
    ?>
    

    To get the url use:

    <body style="background-image:url('<?php echo $image[0]; ?>');">
    
    Login or Signup to reply.
  2. Here’s my preferred way:

    <?php
    $page = get_page_by_title('Title Here'); 
    $image = wp_get_attachment_image_src( get_post_thumbnail_id( $page->ID ), 'full' );
    ?>
    
    <div class="background" style="background-image:url('<?php echo $image[0]; ?>');"/>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search