Escludere i messaggi senza categoria dal ciclo
-
16-10-2019 - |
Domanda
Sto cercando di escludere tutti i messaggi che non hanno una categoria assegnata dal loop principale, ho cercato dappertutto e ho trovato un miliardo di modi per escludere alcune categorie o filtro da categoria specifica, ma non è quello che ho bisogno di fare, si è possibile?
Soluzione
Hi @Raffaele:
The function wp_get_object_terms(...)
can provide you with the information you need. I've written a has_category($post_id)
function that can be used in the loop like this:
<?php while ( have_posts() ) : the_post(); ?>
<?php if (has_category($post->ID)): ?>
<p><?php the_title(); ?></p>
<?php endif; ?>
<?php endwhile; ?>
And here is the has_category()
function:
<?php
function has_category($post_id) {
$has_category = false;
$terms = wp_get_object_terms($post_id,'category');
if (is_array($terms)) {
foreach($terms as $index => $term)
if ($term->slug=='uncategorized')
unset($terms[$index]);
$has_category = (count($terms)>0);
}
return $has_category;
}
Note that my has_category()
function treats posts with the 'uncategorized'
category as having no category. There are probably more performant ways to accomplish this but what you see above should work.
-Mike
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a wordpress.stackexchange