首页 文章

简单查询Wordpress帖子和摘录

提问于
浏览
-1

我想在Wordpress的自定义主页上制作一个“最新消息”部分,输出:

  • 2最近的新闻报道

  • 他们的头衔

  • 摘录

  • 链接

我已经尝试从编码中取出标准循环,看看我先得到了什么,但我什么都没得到 . 我有点困惑,因为我无法弄清楚为什么它甚至没有输出任何帖子,根本没有使用基本循环的内容:

<?php

        // The Query
        $the_query = new WP_Query( 'post_count=2' );

        // The Loop
        if ( $the_query->have_posts() ) {
            echo '<ul>';
            while ( $the_query->have_posts() ) {
                $the_query->the_post();
                echo '<li>' . get_the_title() . '</li>';
            }
            echo '</ul>';
        } else {
            // no posts found
            echo 'No news is good news!';
        }
        /* Restore original Post Data */
        wp_reset_postdata();
?>

此代码目前显示“没有新闻是好消息”的消息 . 有两篇已发布的帖子 .

3 回答

  • 0

    你的代码确实在我这边渲染输出,所以它正在工作 . 你有一个问题, post_count 是一个属性,而不是WP_Query的参数 . 你应该使用 posts_per_page

    我确实发生了为什么你没有得到任何输出,你是使用自定义帖子类型,而不是正常的帖子,在这种情况下,由于你没有任何正常的帖子,所以不会输出任何输出 .

    只需改变这一行

    $the_query = new WP_Query( 'post_count=2' );
    

    $the_query = new WP_Query( 'posts_per_page=2&post_type=NAME_OF_POST_TYPE' );
    
  • 1

    您将变量$ args传递给WP_Query但实际上没有定义它 .

    试试这个:

    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => 2,
        'no_found_rows'  => false,
    );
    
    $the_query = new WP_Query( $args );
    

    然后输出您需要的内容:

    if ( $the_query->have_posts() ) :
        echo '<ul>';
    
        while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <li>
                <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                <?php the_excerpt(); ?>
            </li> 
        <?php endwhile; 
    
        echo '</ul>';
    else :
        // no posts found
        echo 'No news is good news!';
    endif;
    
    wp_reset_postdata();
    

    您不需要为if语句使用此替代语法,但通常以这种方式编写它 .

    我注意到自写这个答案后你更新了你在 'post_count=2' 传递给WP_Query的问题 . 您需要使用 'posts_per_page' 代替 . post_count 是查询对象的属性,而不是参数 .

  • 0

    这应该只返回发布的最后两篇帖子 .

    <?php
    $args=array(
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => 2,
      );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) 
    {
        echo '<ul>';
        while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <li>
            <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
            <?php the_excerpt(); ?>
        </li> 
        <?php endwhile; 
        echo '</ul>';
       <?php
    }
    else
    {
        echo 'No news is good news!';
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>
    

    (上面的帖子略有变化here

相关问题