【问题标题】:Display Category Name via functions.php通过functions.php显示类别名称
【发布时间】:2016-05-11 01:14:54
【问题描述】:

我有一个由 AJAX 更新并使用以下功能的帖子列表:

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);
    }
    ?>

它的工作就像一种享受,但是我无法在正确的列中获取类别名称,您将在 foreach 语句之间看到我所指的列。

我觉得我快到了,但不完全,如果有人能告诉我我做错了什么,那就太好了。

【问题讨论】:

  • 它显示什么与您期望它显示什么?
  • @LucasBonner 目前没有显示任何内容
  • 如果你使用print_r($category);而不是echo …会发生什么?
  • @LucasBonner 我得到这个输出 - Array ( )

标签: php html wordpress categories


【解决方案1】:

声明全局后置变量

global $post;

并使用

get_the_category( $post->ID );

在设置发布数据后在 foreach 中。它应该工作。

【讨论】:

    【解决方案2】:

    改变

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

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

    【讨论】:

    • 我怀疑这会有所帮助,但如果您基于我的回答并使用 get_the_category($post-&gt;ID) 会发生什么?
    猜你喜欢
    • 2020-09-13
    • 2015-01-01
    • 1970-01-01
    • 2012-09-18
    • 2018-10-15
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    相关资源
    最近更新 更多