【问题标题】:WordPress get all post in category functionWordPress获取类别功能中的所有帖子
【发布时间】:2016-12-23 11:11:00
【问题描述】:

我有一个简单的功能,我需要通过类别获取所有帖子,
我有两个类别 Uncategorisedid=1bankid=6

我有三个帖子,bank 类别有 2 个,uncategorised 有 1 个帖子。

我有一个 PHP 文件:

cat_post.php

<?php
global $post;
$myposts = get_posts(array(
    'posts_per_page' => $noOfPost,
    'offset' => 1,
    'category' => $categoryName // set cat here
    ));
echo '<div class="recent-post">';
if ($myposts)
{
    foreach ($myposts as $post) :
        setup_postdata($post);
        ?>

        <a class="col-xs-3 col-md-2" href="<?php the_permalink(); ?>">
        <?php the_post_thumbnail('thumbnail'); ?>
        </a>

        <div class="col-xs-3 col-md-10">
            <a class="" href="<?php the_permalink(); ?>">
                <h2><?php the_title(); ?></h2>
            </a>
        <?php the_excerpt() ?>
            <a href="<?php the_permalink(); ?>">Read Full</a>
            <br>
            <a class="" href="<?php comments_link(); ?>">
        <?php comments_number('0 Comments', '1 Comments', '% Comments'); ?>.
            </a>
        </div>
        <hr/>
        <?php
    endforeach;
    wp_reset_postdata();
}
echo '</div>';

我使用这个PHP文件并将参数设置为:

second_page.php

<div class="tab-content">
    <div class="tab-pane active" id="banks">
        <?php
        $categoryName = 6; // sets category
        $noOfPost = 5; // no of post
        get_template_part('cat_post', get_post_format());  // gets function from cat_post.php
        ?>

    </div>
    <div class="tab-pane" id="morebank">
        <h2>more content</h2>
    </div>
</div>

它显示了来自不同类别的两个帖子,但它应该显示来自 bank 类别的两个帖子。

任何人都知道我做错了什么以及为什么我的代码没有按预期工作?

谢谢。

【问题讨论】:

    标签: php wordpress for-loop


    【解决方案1】:

    尝试使用像这样的global 变量:
    cat_post.php

    <?php
    global $post;
    global $categoryName; //access it through a global variable.
    $myposts = get_posts(array(
        'posts_per_page' => $noOfPost,
        'offset' => 1,
        'category' => $categoryName // set cat here
    ));
    

    并在second_page.php 中设置global $categoryName 值,如下所示:

    ...
    <?php
    global $categoryName;
    $categoryName = 6; // sets category
    $noOfPost = 5; // no of post
    

    希望这会有所帮助!

    【讨论】:

    • 嗯,它似乎适用于有 cmets 的帖子,但如果没有评论,它仍然不会显示,但加 1 寻求帮助
    • @BenjaminOats: 你能在你的second_page.php 文件中写一个get_posts 函数并打印结果,然后检查你是否得到了想要的输出?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多