0

Trying to grab get_the_category() within the loop and post to the byline within the header.

// file1.php
<div>
    <h1><?php the_title(); ?></h2>
    <?php echo $list_categories ; // THIS DOES NOT WORK ?>
</div>

// file2.php
<article>
    <?php
        if ( have_posts() ) : while ( have_posts() ) : the_post();
            $category_array = wp_get_post_categories($post->ID);
            $category_list = array();
            foreach ( $category_array as $categories ) {
                $category_list[] = get_cat_name( $categories );
            }
            $lister = implode(' • ', $category_list);
            $list_categories = $lister;

            echo $list_categories; // THIS WORKS

        endwhile; endif;
    ?>
</article>

What am I missing? It is not echoing on file1.php.

Thanks!

2

I realized that the_title(); can parse in file1.php outside of the loop, so why can't the category and ID? The following solved my issue.

// file1.php
<div>
    <h1><?php the_title(); ?></h2>
    <?php
        $category_array = wp_get_post_categories($post->ID);
        $category_list = array();
        foreach ( $category_array as $categories ) {
            $category_list[] = get_cat_name( $categories );
        }
        $lister = implode(' • ', $category_list);
        $list_categories = $lister;
        echo $lister ;
    ?>
</div>

// file2.php
<article>
    <?php
        if ( have_posts() ) : while ( have_posts() ) : the_post();
            the_content();
        endwhile; endif;
    ?>
</article>

Alternatively, to pass the category link, you could use the following (warning, changed variables below):

<ul>
    <?php
        // get post categories
        $cats = wp_get_post_categories($post->ID);
        foreach ( $cats as $category ) {
            echo "<li>";
            $current_cat = get_cat_name($category);
            $cat_link = get_category_link($category);
            echo "<a href='$cat_link'>";
            echo $current_cat;
            echo "</a>";
            echo "</li>";
        }
    ?>
</ul>
  • 1
    or in other words, the relevant globals are set to the first post in the results of the query which what makes this kind of code work even before the loop had started, but you could also start the loop and then rewind it, – Mark Kaplun Jul 7 '16 at 19:59
  • Great point. However, Isn't loop rewinding an outdated function? I could be mistaken. – Alexander Graham Jul 7 '16 at 20:02
  • just because it is used rarely doesn't mean it should not be used ;) IIRC it just change the place counter and sets the globals to the right post again. – Mark Kaplun Jul 7 '16 at 20:06
  • Great point again, will check it out. Thanks Mark! – Alexander Graham Jul 7 '16 at 20:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.