Forums

[resolved] Need some help with a php if statement (3 posts)

  1. lochmc
    Member
    Posted 1 year ago #

    Hi guys,

    I don't have the strongest PHP skills and I need a little bit of help with the following.

    Right now I'm using 2 seperate statements like so.

    1.

    <?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="header" style="background-image:url('<?php echo $image[0]; ?>');">
    	<?php endif; ?>

    2.

    <?php if (is_front_page() || is_home()) {?>
    	<div id="header" class="slide">
    	<?php } ?>

    What I need is for <div id="header"> to be generated regardless of what page you're on. This is a fallback in case the user hasn't set a featured image.

    If the page has a featured image then I need the #header to have that image as it's background, which I've accomplished with the code in #1 above.

    Then on the homepage, I'm going to have the background image run through a series of slides, so I need something like <div id="header" class="slide"> like I've put in #2 above.

    It's probably pretty simple. I hope I've explained myself cleary enough for someone to understand.

    Thanks for the help.

  2. JPry
    Member
    Posted 1 year ago #

    Assuming the code you've posted is working correctly for your site, then you'd probably want something like this:

    <?php
    $headerAttributes = "";
    if ( has_post_thumbnail( $post->ID ) ) {
        $image = wp_get_attachment_image_scr( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
        $headerAttributes = $headerAttributes . " " . 'style="background-image: url(' . $image[0] . ')"';
    }
    if ( is_front_page() || is_home() ) {
        $headerAttributes = $headerAttributes . ' class="slide"';
    }
    echo '<div id="header"' . $headerAttributes . '>';
    ?>

    This is just one of many ways to do this, but it should give you enough of an idea to tailor it to your own style.

  3. lochmc
    Member
    Posted 1 year ago #

    Thanks for the help, JPry. Perfect! Although you mispelt wp_get_attachment_image_scr :)

    Just pasting final code in case anyone else ever needs to use this.

    <?php
    $headerAttributes = "";
    if ( has_post_thumbnail( $post->ID ) ) {
    	$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
    	$headerAttributes = $headerAttributes . " " . 'style="background-image: url(' . $image[0] . ')"';
    }
    if ( is_front_page() || is_home() ) {
    	$headerAttributes = $headerAttributes . ' class="slide"';
    }
    echo '<div id="header"' . $headerAttributes . '>';
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags