Forums

Add PHP to a Function - Category Thumbnails (4 posts)

  1. imikedesigns
    Member
    Posted 3 months ago #

    So I have this function that is working great to pull a default thumbnail if there is no featured thumbnail. But, I want to combine it with some code to pull a thumbnail based on the posts category. I have both working codes but im unsure how to combine the two properly, syntax wise. Here is my function:

    function catch_that_image() {
      global $post, $posts;
      $first_img = '';
      ob_start();
      ob_end_clean();
      $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
      $first_img = $matches [1] [0];
    
      if(empty($first_img)){ //Defines a default image
        $first_img = "/images/default-blog-image.jpg";
      }
      return $first_img;
    }

    Now instead of a static image I want to get this code into the $first_img variable.

    <?php $category = get_the_category(); echo $category[0]->cat_name; ?>.jpg

    This will allow me to add simply upload an image with the category name as a title like new.jpg. Then anything in the category named news will use this thumbnail. Thanks for any help.

  2. deepbevel
    Member
    Posted 3 months ago #

    This would be easy for an image on category/archive pages:

    <?php
    if (is_category('your category slug')) { ?>
    	<h2 class="cat-title">
    <img src="image url">
    </h2>

    But sounds like you want the image where ever the post appears,
    maybe this will help:
    can-i-set-a-default-featured-image-for-a-category

  3. imikedesigns
    Member
    Posted 3 months ago #

    Thanks for the reply. It is a archive that im working on and the code you posted is basically what im doing. But, im using conditionals to show an the post thumbnai if it is set, if not, grab the first image from the post, and if no image is used in the post, use a default image for that category. So its an if else statement im using. The function I posted will grab the first image from the post and if not it will display an image i define. But, rather than a defined image, i need it to pull an image based on category name, which is what that line of code i posted does. So i need that jammed inside this function but I dont know how. The code im using is from the page you linked to actually. Thanks again.

  4. deepbevel
    Member
    Posted 3 months ago #

    ahh, okay, I'll let you know if anything comes up on it. A bit complex for me but that's a nice feature I wouldn't mind figuring out myself.

Reply

You must log in to post.

About this Topic