[resolved] Use Featured image as background image (2 posts)

  1. rioforce
    Posted 1 year ago #

    Hi, I am new to PHP, so I am having some difficulty with this. I just enabled Featured Images in Functions.php on my site with a line of code. I want to use the featured image on the page as the background image. I found this code on the WordPress Codex.


    I copied that code and put it in the header.php of my site like it said. In the <head> tag, below the wp_head(). Here's what the <head> looks like:

    	<title><?php wp_title(); ?> <?php bloginfo('name'); ?></title>
    	<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
    	<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
    	<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
    	<?php if ( is_singular() ) wp_enqueue_script( 'comment-reply' ); ?>
    	<?php wp_head() ?>
        // declare $post global if used outside of the loop
        global $post;
        // check to see if the theme supports Featured Images, and one is set
        if (current_theme_supports( 'post-thumbnails' ) && has_post_thumbnail( $post->ID )) {
            // specify desired image size in place of 'full'
            $page_bg_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
            $page_bg_image_url = $page_bg_image[0]; // this returns just the URL of the image
        } else {
            // the fallback – our current active theme's default bg image
            $page_bg_image_url = get_background_image();
        // And below, spit out the <style> tag... ?>
        <style type="text/css" id="custom-background-css-override">
            body.custom-background { background-image: url('<?php echo $page_bg_image_url; ?>'); }

    Is that where it was supposed to be put? I wasn't sure if it's supposed to be in page.php (the page template) or header.php, because that page said "this should be used in the <head> of the page template".

    What is going on? My site is Localhost right now, so I cannot link it. But if you need anymore snippets of code, just tell me. :)

    Thanks for the help!

  2. rioforce
    Posted 1 year ago #

    I have figured it out!

    I have to add !important at the end of this line (right before the simicolon).

    body.custom-background { background-image: url('<?php echo $page_bg_image_url; ?>'); }

    It has broken the alignment of my background image for some reason. Hopefully I can get that fixed now. I'll probably have to do it with CSS.

    EDIT: Never mind about the alignment, I accidentally changed it.

Topic Closed

This topic has been closed to new replies.

About this Topic