【问题标题】:How to show categoy of the post in recents posts widget wordpress?如何在最近的帖子小部件 wordpress 中显示帖子的类别?
【发布时间】:2019-02-25 07:06:02
【问题描述】:

我的 wordpress 网站右侧边栏上有一个最近的帖子小部件,它显示来自多种帖子类型的最近帖子。我希望这个小部件还显示帖子的帖子类型或类别。 我怎样才能做到这一点?

【问题讨论】:

    标签: php wordpress widget


    【解决方案1】:

    在循环中使用这个get_the_category($id)

    要手动执行此操作(即通过创建自己的函数),请将其添加到函数中并在需要时调用它

    <ul>
        <?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>
        <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
    
            <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
            <li><?php get_the_category(the_ID())->name; // caetgory name ?></li>
    
            <?php 
        endwhile;
        wp_reset_postdata();
        ?>
    </ul>
    

    【讨论】:

    • 你能解释一下我把这条线放在哪里吗?我也不想修改 wordpress 的核心
    • 非常感谢@Yemi,我知道如何注册短代码并调用它们或其他任何东西,但我想要的是更像是在现有小部件或其他东西中设置,而不接触代码文件.无论如何谢谢:)
    【解决方案2】:

    您可以在 sidebar.php 中为最近的帖子编写代码

    <?php
    $args = array( 'numberposts' => '3' );
    $recent_posts = wp_get_recent_posts( $args ); ?>
    <ul>
        <?php foreach( $recent_posts as $recent ){ ?>
    
                <li>
                    <a href="<?php echo get_permalink( $recent['ID'] ); ?>">
                        <img src="<?php echo get_the_post_thumbnail_url( $recent['ID'] ); ?>">
                        <div class="recent_post_meta">
                            <span>
                            <?php $category_detail = get_the_category( $recent['ID'] );//$post->ID
                                foreach( $category_detail as $cd ){
                                echo $cd->cat_name;
                                } ?>
                            </span>
                            <div class="post_side_title">
                                <?php echo get_the_title( $recent['ID'] ); ?>
                            </div>
                        </div>
                    </a>
                </li>
    
        <?php } ?>
        </ul>
    

    【讨论】:

      猜你喜欢
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多