WordPress.org

Ready to get started?Download WordPress

Forums

Specific Header for a Specific Post (5 posts)

  1. travelingtalisman
    Member
    Posted 6 years ago #

    I'm attempting to link a specific header image to a specific post. This is simple to do if the post is being linked to directly as a single post. I can use this:

    if(is_single("page-title")
    $background_image = "background1.jpg";

    But when the post is approached as an archive or a search, using this doesn't work:

    if(is_paged("page-title") || is_archive("page-title") || is_search("page-title"))
    $background_image = "background1.jpg";

    There must be some way that the code knows that "/page/3/" is the same post-id as "year/month/day/page-title".

    Does anybody have a clue? Thanks so much for any input.

  2. Adam Brown
    Member
    Posted 6 years ago #

    To clarify: For one particular post, you want to replace the post title with an image instead of text, right?

    In your theme's functions.php, try adding this (with some obvious modifications that I think you'll figure out):

    <?php
    function myTitleFilter($t){
      if ($t != 'The title I want to replace')
       return $t;
      $t = '<img src="" alt="'.$t.'" />';
      return $t;
    }
    add_filter('the_title','myTitleFilter');
    ?>

    (If you want it to work in any theme, put it into a file in your plugins folder (with the required plugin file comment header) instead of in your theme's functions.php.)

  3. travelingtalisman
    Member
    Posted 6 years ago #

    Persistence pays. I found an answer that works everywhere.
    I put this code in the header file:

    $title = the_title('','',false);
    $title = sanitize_title($title);

    if($title == "title1")
    $background_image = "background1.jpg";
    elseif($title == "title2")
    $background_image = "background2.jpg";

  4. travelingtalisman
    Member
    Posted 6 years ago #

    Ah, a function. Yes more efficient.

    Ok, I made it simpler. I named my background images the same as the titles of the posts I want them linked to.

    Here's my function:

    function get_background_image($title = "")
    {
    $title = sanitize_title($title);
    if(file_exists($_SERVER["DOCUMENT_ROOT"] . "/path-to-image/" . $title . ".jpg"))
    $background_image = $title . ".jpg";
    else
    $background_image = "default_header.jpg";
    return $background_image;
    }

    And I put this in my header file:

    #header{ { background: url("<?php bloginfo('stylesheet_directory'); ?>/images/<?=get_background_image(the_title('','',false))?>") repeat-y top; border: none; }

  5. Adam Brown
    Member
    Posted 6 years ago #

    Glad you got it working. In future, remember to use backticks when pasting code.

Topic Closed

This topic has been closed to new replies.

About this Topic