0
votes

I'm having trouble displaying the loop category correctly. Need display only one category in lit posts. Why the first post gets all selected categories and the next posts already have the correct display of one category. How can I make only the current selected category displayed in the first post? My code looks like this. I attached the picture.

My loop custom post

<?php
/* Start the Loop */
$args = array( 'post_type' => 'database',
               'posts_per_page' => 10,
               'paged' => $paged,
               'post_status' => 'publish',
               'ignore_sticky_posts' => true,
               'order' => 'DESC', 
               'orderby' => 'date');

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();

This is for display one category in loop post

<?php   
// Get terms for post
$terms = wp_get_post_terms( $post->ID , 'database_categories' ,$args2);
$args2 = array( 'parent' => 39,
                'fields' => 'all');

// Loop over each item since it's an array
if ( $terms != null ) {
    foreach( $terms as $term ) {
        $term_link = get_term_link( $term, 'database_categories' );
        // Print the name and URL
        echo '<a href="' . $term_link . '">' . $term->name . '</a> ';
// Get rid of the other data stored in the object, since it's not needed
unset($term); 
    } 
} 
?>      

my loop image

1

1 Answers

0
votes

If the object here is to get the first term and ignore the rest then I would just shift off the first array element and no need for a loop on terms.

$args2 = array('parent' => 39, 'fields' => 'all');
$terms = wp_get_post_terms( $post->ID , 'database_categories' ,$args2);

if (!empty($terms)) {
    $term = array_shift($terms);
    echo sprintf('<a href="%s">%s</a>', get_term_link( $term, 'database_categories' ), $term->name);
}