0
votes

I want to display placeholder image if there is no category image and no featured image for a post

Then if there is a category image display then instead

Then if there is a featured image for a post display this instead

    <?php if (has_post_thumbnail()) { ?>
        <img src="<?php echo the_post_thumbnail_url(); ?>" class="single-blog-post-image" alt="Post Featured Image" />
    <?php } else {
        $category = get_the_category();
        $categoryImage = 'http://akjservices.foamydev.com/wp-content/uploads/'.$category[0]->category_nicename.'.png';
            if (!has_post_thumbnail() && file_exists($categoryImage)) {
            ?>
            <img class="single-blog-post-image" src="<?php bloginfo('url'); ?>/wp-content/uploads/<?php echo $category[0]->category_nicename ; ?>.png" alt="Category Featured Image" />
            <?php } else { ?>
                <img src="/wp-content/themes/akj/img/placeholder-part-image.jpg" alt="AKJ Services Default Image" class="single-blog-post-image">
     <?php } }?>

It is working apart from it only gets the category image from the very first category nothing else

How can I amend my code to fix it so I can get any post category image?

Can see an example here

http://akjservices.foamydev.com/product/fr-sfj-2-7-5k/ => default placeholder image

The code specifies that the image name must be the same as the category name for example A06B-6044.png - however happy to ignore this and for it just to show the category image no matter what the name is.

1
Having (!has_post_thumbnail) in your if statement, is redundant. Can you explain what you mean by very first category image with an example of what you expect vs what you're getting please? developer.wordpress.org/reference/functions/get_the_category - pendo
my code was working so that akjservices.foamydev.com/product/a06b-6044-h009 would display the category image when uploaded with the correct category name as A06B-6044 is the first post category. - however now it does not work either.. these pages are using default wordpress post type to create "part" pages on the site - Lottie
What do you get when you var_dump(file_exists($categoryImage)); and var_dump($categoryImage); before your if statements - pendo
If you're outside the loop for get_the_category(), it's going to get all categories. If you want it to get JUST the category for the current post, you need to be inside the loop or explicitly pass it the postid get_the_ID() - pendo

1 Answers

0
votes

You should loop the categories, You are accessing the only first one, don't forget to remove [0] after $category then.

$categories = get_the_category()
foreach( $categories as $cateogry ){
  $category->category_nicename;
  ...
}