WordPress.org

Ready to get started?Download WordPress

Forums

Best Practices - inserting conditional element in header (5 posts)

  1. marenm
    Member
    Posted 3 years ago #

    Hello,

    I am relatively new to PHP and would like to know the best way to conditionally add an HTML element and script to the header.php file of my custom theme.

    I've done a lot of searching around and most of the tutorials out there seem really roundabout and impractical.

    Basically, I'd like to add an HTML 5 canvas element (and then a processing.js script) to the header of my theme on the HOME page only.

    Does anyone have thoughts on this? Can maybe point me in the right direction? I'm a little bit confused about filters and hooks, but that seems like the best way to do it.

  2. ambrosite
    Member
    Posted 3 years ago #

    I would use one of the built-in conditional tags -- either is_home or is_front_page depending on how you have things set up.

    http://codex.wordpress.org/Conditional_Tags

  3. Steffen Jørgensen
    Member
    Posted 3 years ago #

    <?php if (is_home() ) : ?>
    <canvas>...</canvas>
    <?php endif; ?>
  4. marenm
    Member
    Posted 3 years ago #

    Sorry, I don't think I was being very clear with my question.
    First, my custom theme is a child theme.
    I understand the Conditional Tag part. I'm wondering where exactly I should put that code (and how to put it there) because I'd like to do it via the functions.php file.
    I don't really understand how to insert it via a hook or filter.
    Thanks!

  5. Rev. Voodoo
    Volunteer Moderator
    Posted 3 years ago #

    Are you adding code into the actual <head> section?

    If so check this out...
    http://voodoopress.com/2011/02/add-a-favicon-to-your-theme-with-a-simple-hook/

    it's for adding a favicon, BUT the code is the hook for adding stuff to your <head> section. You can put any code you like in there. I add a variety of stuff to my <head> using that method.

    If you aren't adding to the actual <head> section, but are just adding to the header (as in the html output part of the header) then whether or not you can do it from functions.php would depend on what your theme has available to hook into. It may or may not be possible

Topic Closed

This topic has been closed to new replies.

About this Topic