• From searching on this forum and others I have found this code (which works)

    <?php if (has_post_thumbnail( $post->ID ) ): ?>
    <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
    <div id="category-name" style="background-image: url('<?php echo $image[0]; ?>')">
    
    </div><!-- end #category-name -->
    <?php endif; ?>

    What I need now is the Else statement – to set the background to a default image if there isn’t a specified “featured image”.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter wwalker

    (@wwalker)

    Also some styling full width, no repeat, partially translucent, etc…

    if / else / endif

    https://php.net/manual/en/control-structures.elseif.php

    example:

    <?php if (has_post_thumbnail( $post->ID ) ): ?>
    <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
    <?php else :
    $image = get_bloginfo( 'stylesheet_directory') . '/images/default_cat_img.jpg'; ?>
    <?php endif; ?>
    <div id="category-name" style="background-image: url('<?php echo $image[0]; ?>')">
    
    </div><!-- end #category-name -->

    assuming the image is named default_cat_img.jpg and is located in the images folder of the theme.

    you could also set the default image in style.css (example):

    .category-name { background: url(images/default_cat_img.jpg) center top no-repeat; }

    styling is css – have a lok here: https://www.w3schools.com/css/

    Thread Starter wwalker

    (@wwalker)

    I think the problem I am having is when there is no feature image, the formula still returns a character or two.
    For example, when there is no feature image, the above formula sets the background image to <div id="category-name" style="background-image: url('h')">

    ideas?

    my mistake – i was not aware of the $image[0] in the background url –

    adapted, try:

    <?php if (has_post_thumbnail( $post->ID ) ): ?>
    <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
    $image = $image[0]; ?>
    <?php else :
    $image = get_bloginfo( 'stylesheet_directory') . '/images/default_cat_img.jpg'; ?>
    <?php endif; ?>
    <div id="category-name" style="background-image: url('<?php echo $image; ?>')" >
    
    </div><!-- end #category-name -->
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Set featured image as div background’ is closed to new replies.