Sam Kelham
Sam Kelham

Reputation: 1467

Display Category Name via functions.php

I have a list of post that is being updated by AJAX and using this function below:

function prefix_load_cat_posts () {
    $cat_id = $_POST[ 'cat' ];
    $args = array (
        'cat' => $cat_id,
        'posts_per_page' => -1,
        'order' => 'DESC'

        );

    $posts = get_posts( $args );

    ob_start (); ?>

    <table class="table">
        <tbody>
            <tr cellpadding="20">
                <th valign="bottom">Date</th>
                <th valign="middle">Posted By</th>
                <th valign="middle">Name</th>
                <th valign="middle">Category</th>
                <th valign="middle">Description</th>
                <th valign="middle">Property/ Project</th>
                <th valign="middle">File</th>
            </tr>

    <?php $category = get_the_category(); ?>

    <?php foreach ( $posts as $post ) {
        setup_postdata( $post ); ?>

        <tr>
            <td><?php echo get_the_date( 'j M Y',$post->ID ) ; ?></td>
            <td><?php the_author(); ?></td>
            <td><?php echo get_field('attachment_name',$post->ID); ?></td>

            <td><?php echo $category[0]->cat_name ; ?></td>

            <td><?php echo get_field('attachment_desc',$post->ID); ?></td>
            <td><?php echo get_field('property/_project',$post->ID); ?></td>
            <td><a href="<?php echo get_field('attachment_document',$post->ID); ?>">Download PDF</a></td>
        </tr>

        <?php } wp_reset_postdata(); ?>

        </tbody>
    </table>

        <?php $response = ob_get_contents();
        ob_end_clean();

        echo $response;
        die(1);
    }
    ?>

Its working a like a treat, however I cant get the category name to pull through in the correct column, you will see the column I am referring to in-between the foreach statements.

I feel like I am nearly there but no quite, If any one can show me what I am doing wrong, that would be great.

Upvotes: 1

Views: 1763

Answers (2)

Deepti chipdey
Deepti chipdey

Reputation: 1177

declare global post variable

global $post;

and use

get_the_category( $post->ID );

inside foreach after setup post data. it should work.

Upvotes: 1

Lucas Bonner
Lucas Bonner

Reputation: 849

Change

<?php $category = get_the_category(); ?>

<?php foreach ( $posts as $post ) {
    setup_postdata( $post ); ?>

to

<?php foreach ( $posts as $post ) {
    setup_postdata( $post ); 
    $category = get_the_category(); ?>

Upvotes: 0

Related Questions