I'm trying to find a way to get my posts with different look depending on their category.
I have first tried to do it using the template hierarchy but it seems there is no pattern for the category posts. (ie single-cat-mycategory.php)
So then within single.php I tried the conditional tagging using is_category()
but my understanding it's only working for the archive
pages.
Finally, I'm now trying to use the is_single()
conditional tagging where first I'm looking for all the posts corresponding to my category and pass it as a parameter of is_single()
In functions.php
function get_post_id_by_cat(){
$args = [
'post_type' => 'post',
'post_status' => 'publish',
'category_name' => 'my_category',
];
$cat_query = new WP_Query( $args );
if ($cat_query -> have_posts()){
while ($cat_query -> have_posts()){
$cat_query -> the_post();
$post_ids[] = get_the_ID();
}
wp_reset_postdata();
}
In single.php
$my_cat_posts = get_post_id_by_cat();
if (is_single($my_cat_posts)) {
while ( have_posts() ) : the_post();
//do my stuff here
endwhile;
}
My first question is this in term of Wordpress design a good way to do this or is there a better way as my concern is mainly for performance, with this method.
If it's ok,
My issue is that $post_ids
is storing the data in a php object format and not an array so is_single()
doesn't get the posts ids properly as parameter.
And i don't get how I can get it converted to an array.
$post_ids[] = to_array(get_the_ID());
return
Uncaught Error: Call to undefined function to_array()
or
$post_ids[] = (array)get_the_ID();
return each post ids stil has object but within a array like this:
array(8) {
[0]=>
array(1) {
[0]=>
int(5415)
}…
or
$post_ids[] = get_object_vars(get_the_ID());
return
get_object_vars() expects parameter 1 to be object, integer given
But if pass this array it does work properly:
$array = ['5415','5413','5411','5401'];
Hope this is clear enough,
Thanks for any input!
Matth.