WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Need to add sponsor banner before posts on Category archive page (10 posts)

  1. bigcityjohn
    Member
    Posted 3 years ago #

    I'm trying to add a sponsor banner on a particular Category archive page, and it should appear just above the posts on that specific category page. I'm using the following code in my functions.php file, but the banner is appearing above each and every post on that page rather than just above the first one.

    Can someone please let me know what I'm doing incorrectly? Or, if there's a better/more concise way of doing this, please feel free to share.

    function sponsor_banner($post_count) {
    if (is_category('category-xyz')) {
    if ($post_count == 1) { ?>
    <img src="/path/to/banner.jpg">
    <?php
    }
    }
    }
    add_action('the_post', 'sponsor_banner');
  2. esmi
    Forum Moderator
    Posted 3 years ago #

  3. Mike Little
    Member
    Posted 3 years ago #

    Try this:

    function sponsor_banner($post_count) {
      static $already_run = false;
      if (is_category('uncategorized')) {
        if ( !$already_run) {
    ?>
    <img src="/path/to/banner.jpg">
    <?php
          $already_run = true;
        }
      }
    }
    add_action('the_post', 'sponsor_banner');
  4. bigcityjohn
    Member
    Posted 3 years ago #

    Thank you so much! This did the trick perfectly. I don't understand everything in the code, but I'm happy that I don't have to tinker around for another 6 hours. :-)

  5. Mike Little
    Member
    Posted 3 years ago #

    A minor correction: The parameter passed to the_post hook is the post itself

    function sponsor_banner($post) {
      static $already_run = false;
      if (is_category('uncategorized')) {
        if ( !$already_run) {
    ?>
    <img src="/path/to/banner.jpg">
    <?php
          $already_run = true;
        }
      }
    }
    add_action('the_post', 'sponsor_banner');
  6. bigcityjohn
    Member
    Posted 3 years ago #

    I appreciate the update. I would have never figured this out on my own.

  7. DeveWeb
    Member
    Posted 2 years ago #

    thanks for the code, But I have a problem trying to put the code gives me an error, the code is put in functions.php theme / yourtheme / functions.php? I tried but I get error when I add the code line?

  8. DeveWeb
    Member
    Posted 2 years ago #

    SOS guyss How to ADD this code pleaseee :(

  9. Mike Little
    Member
    Posted 2 years ago #

    The code needs to be added to your theme's functions.php file.

    If you have any other problems, please start a new topic, this one has been marked as resolved.

  10. DeveWeb
    Member
    Posted 2 years ago #

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.