【问题标题】:WordPress Sticky Post on Homepage onlyWordPress Sticky Post 仅在主页上
【发布时间】:2018-08-03 02:04:10
【问题描述】:

试图在我的客户主页上显示一个英雄区域显示最近的置顶帖子,但我似乎一直遇到障碍。代码末尾的错误使我在死亡时得到白屏。这是我的代码:

<?php if (is_home()) {
            $sticky = get_option( 'sticky_posts' ); // Get all sticky posts
            rsort( $sticky ); // Sort the stickies, latest first
            $sticky = array_slice( $sticky, 0, 1 ); // Number of stickies to show
            query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) ); // The query
            if (have_posts() ) { while ( have_posts() ) : the_post(); ?>
            <div class="trend-post">
            <div class="thumb"><?php the_post_thumbnail(); ?></div>
            <div class="title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></div></div>
            <?php endwhile;?>
            <?php wp_reset_query()?>
        }
?>

【问题讨论】:

  • wp_reset_query() 后面少了一个分号。另外,您是否尝试将define( 'WP_DEBUG', true ); 添加到您的 wp-settings.php 文件以启用错误报告?

标签: php wordpress sticky website-homepage


【解决方案1】:

在您的代码中,您忘记为第二个if statement -&gt; if(have_posts()) 添加结束}。另外我认为您不需要使用rsortarray_slice 来获取第一个最新的置顶帖子。您可以尝试使用下面的编辑代码(未经测试,但应该可以): 这将显示第一个最新的置顶帖子。如果没有置顶帖子,则将显示第一个最新的非置顶帖子。

<?php if (is_home()) {
            $sticky = get_option( 'sticky_posts' ); // Get all sticky posts

            $args = array(
                  'posts_per_page' => 1,
                  'post__in'  => $sticky,
                  'ignore_sticky_posts' => 1
            );
            $query = new WP_Query( $args );

            if( $query->have_posts() ) {
                  while( $query->have_posts() ) {
                        $query->the_post();
                  ?>
                        <div class="trend-post">
                        <div class="thumb"><?php the_post_thumbnail(); ?></div>
                        <div class="title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></div></div>
                  <?php
                  }
                  wp_reset_query();
            }
        }
?>

【讨论】:

  • 该死!我怎么错过了?谢谢。一定是我最近完成的所有工作......
【解决方案2】:

你可以试试这个代码

<?php
    $sticky = get_option( 'sticky_posts' );
    rsort( $sticky );
    $sticky = array_slice( $sticky, 0, 1 );

if (is_numeric($sticky&#91;0&#93;)) {
    /* Query sticky posts */
    query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) );
        while ( have_posts() ) : the_post();
        the_title('<h3>', '</h3>');
        if($post->post_excerpt) :
            the_excerpt();
        else:
            the_content();
        endif;
        endwhile; // End the loop. Whew. 

    wp_reset_query();
}
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-15
    • 2014-05-25
    • 2021-03-14
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    相关资源
    最近更新 更多