【问题标题】:Display category post list based on the current posts category根据当前帖子类别显示类别帖子列表
【发布时间】:2021-11-28 08:09:25
【问题描述】:

有人知道如何根据当前帖子页面当前类别显示 WordPress 帖子列表吗?

例如,如果我目前在 post333.html 上,并且页面所属的类别是“Drinks”。

如何让该类别下的其余帖子显示在 post333.html 上的“建议主题”列表中。

如果帖子和类别发生变化,列表也会发生变化。

【问题讨论】:

    标签: javascript php html wordpress


    【解决方案1】:

    以下代码应直接进入您的模板文件。

    <?php
    // Get Other posts in same category 
    $suggested_posts = get_posts( array( 
        'category__in' => wp_get_post_categories( $post->ID ), // Retrieve the list of categories for a post.
        'numberposts' => 5, // Number of posts
        'post__not_in' => array( $post->ID ) // Exclude current post
    ) );
    
    // If post found
    if( $suggested_posts ) {
        foreach( $suggested_posts as $post ) {
            setup_postdata($post); ?>
            <ul> 
                <li>
                <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
                    <?php the_content('Read the rest of this entry &raquo;'); ?>
                </li>
            </ul>   
        <?php }
    }
    wp_reset_postdata(); 
    ?>
    

    如果你想在任何地方使用它,那么你可以创建一个如下所示的短代码。

    <?php
    function yourprefix_suggested_posts( $atts ){
        // Get Other posts in same category 
        $suggested_posts = get_posts( array( 
            'category__in' => wp_get_post_categories( $post->ID ), // Retrieve the list of categories for a post.
            'numberposts' => 5, // Number of posts
            'post__not_in' => array( $post->ID ) // Exclude current post
        ) );
    
        // If post found
        if( $suggested_posts ) {
            foreach( $suggested_posts as $post ) {
                setup_postdata($post); ?>
                <ul> 
                    <li>
                    <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
                        <?php the_content('Read the rest of this entry &raquo;'); ?>
                    </li>
                </ul>   
            <?php }
        }
        wp_reset_postdata();    
    }
    add_shortcode( 'suggested_posts', 'yourprefix_suggested_posts' );
    ?>
    

    以后你可以在任何地方使用[suggested_posts]短代码。

    (未测试,但应该可以。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-06
      • 2016-06-13
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多