【问题标题】:Showing only one category on wordpress homepage在 wordpress 主页上只显示一个类别
【发布时间】:2014-07-03 16:19:04
【问题描述】:

我试图在我的主页上只显示一个类别。为此,我知道我必须编辑 index.php 文件,但我不知道为什么我的代码没有使用。在这种情况下,我要显示的帖子类别的ID是“1”

这是代码(我的编辑是最后一行):

<div class="row">

    <!-- Contains the loop of all posts -->
    <div class="col-md-8" id="post-container">

        <!-- Start the Loop. -->
 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
 <?php if (in_category('1')&& is_home()) continue; ?>

有什么想法吗?

免责声明:我一点也不精通 php,只是有人告诉我这应该是一个容易解决的问题。

【问题讨论】:

    标签: php wordpress categories posts


    【解决方案1】:

    为了正确执行此操作,您需要对主页的数据运行过滤器...其他答案和您正在执行的操作将无法正常使用分页...例如,如果最后 X 个帖子是'不在您要显示的类别中,您将获得 0 个或更少的结果...

    你想以这种方式运行过滤器..

    function exclude_category( $query ) {
        if ( $query->is_home() && $query->is_main_query() ) {
            $query->set( 'cat', 'YOUR CATEGORY ID HERE' );
        }
    }
    add_action( 'pre_get_posts', 'exclude_category' );
    

    这将正常工作,让您仍然可以使用适当的分页。您可以在此处找到有关过滤器的更多信息 -> http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

    巴特

    【讨论】:

    • 这个答案+1。这是正确的做法。
    【解决方案2】:

    试试&lt;?php if (in_category(1)&amp;&amp; is_home()) continue; ?&gt;。 ID 必须是整数,否则将被视为 slug。

    【讨论】:

      【解决方案3】:

      More info for argument

      <?php $args = array(
          'orderby'            => 'name',
          'order'              => 'ASC',
          'style'              => 'list',
          'include'            => '',
          'hierarchical'       => 1,
          'title_li'           => __( 'Categories' ),
          'show_option_none'   => __( 'No categories' ),
          'number'             => 1,
          'taxonomy'           => 'category',
          'walker'             => null
      ); ?>
      
      <?php if (is_home()) { ?>
       <ul class="categories">
         <?php wp_list_categories($args); ?>
       </ul>
      <?php } ?>
      

      【讨论】:

        【解决方案4】:

        与其浏览所有帖子并过滤掉您想要的帖子,

        尝试使用

        query_posts('cat=1');

        //这将改变主循环,然后你可以有更多的控制,比如每页发帖等等

        if ( have_posts() ) : while ( have_posts() ) : the_post();

        【讨论】:

        • query_posts 应该绝不被使用
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多