There are several fatal assumptions here, and, a far better way to do it.
1. Declaring Functions inside Functions
This will cause a fatal error in a future version of PHP, makes it super difficult to debug. But worst, it’s completely unnecessary.
This:
function foo () {
function bar () {
//
}
bar();
}
Should just be this:
function bar() {
//
}
function foo() {
bar();
}
2. Comparing strings and numbers, with a fuzzy in_array
1
is not "1"
, but because the 3rd parameter was never set to true, 1
is "1"
. It’s also true
, and lots of other “truthy” values.
3. Relying on hardcoded magic values
Don’t hardcode the category ID. If you delete it by accident and recreate it, the ID will change. If you migrate to a new site the ID will change. It’s very easy to break.
If you can’t let the user pick a term, at least use a known slug/name so it can be recreated/set.
4. Assuming the functions would return category IDs
wp_get_post_categories
does not return category IDs or category names. It returns term objects. These objects contain names, descriptions, IDs, etc. I expect your code to be generating PHP warnings.
5. Hardcoding Inline Styles
You shouldn’t use inline styles. Use HTML classes
The Correct Way To Do It
Use post_class
to print out the posts html classes:
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
This gives you classes you can target with CSS for post type, tags, categories, ID, etc etc. It does this automatically, so you doon’t have to tell it to add the class.
Here’s an example from my own site:
<article id="post-931" class="post-931 post type-post status-publish format-standard has-post-thumbnail hentry category-development category-gutenberg tag-block-editor tag-comments tag-gutenberg tag-javascript tag-plugins tag-react tag-releases tag-wordpress">
post_class
automatically generated those HTML classes for me, andif I added that post to a category named test
, then category-test
would appear on the frontend as a HTML class too.
So now you can target all posts in a category with a CSS file, resulting in nicer styling, smaller HTML, and easier to understand code, e.g.
.category-development {
background: red;
}
Now all posts I write in the development
category have a red background.
Don’t forget the body_class
function too. It adds HTML classes for the template used, archives, etc
A final note, don’t end your PHP files in ?>
. It’s not necessary and can actually cause an easily missed mistake with stray spaces aftering the closing tag breaking sites on older PHP versions.