首页 视频课程 主题开发课程第05章、文章输出 WordPress置顶文章与文章列表结构控制

WordPress置顶文章与文章列表结构控制

2023-06-11 / 252阅

WordPress置顶文章与文章列表结构控制

WordPress是一款非常强大的博客和网站建设平台,为用户提供了很多灵活的功能和插件,其中包括置顶文章和文章列表结构控制。

1. WordPress置顶文章

WordPress的置顶文章功能可以让你将一篇文章置顶到博客或网站的首页或特定分类的顶部位置,使其更加突出和醒目。置顶文章功能理解为促销活动,或是将精美的文章放在首位,以吸引访客注意。

1.1 代码实现

使用以下代码将文章置顶,在写的时候可以选择用特定的分类来表示置顶内容:

$sticky_post_args = [
  'post_type' => 'post',
  'posts_per_page' => 1,
  'post__in' => get_option( 'sticky_posts' ),
  'ignore_sticky_posts' => 1,
  'category' => 1
];

$sticky_posts = new WP_Query( $sticky_post_args );
if ( $sticky_posts->have_posts() ) :
  while ( $sticky_posts->have_posts() ) : $sticky_posts->the_post();
    // DO STUFF
  endwhile;
endif; 

1.2 效果展示

置顶文章被放置在首页或特定分类的顶部位置。

2. WordPress文章列表结构控制

在WordPress中,可以通过更改文章列表的结构来改善用户读取内容的体验。它往往包括添加图片、格式化文本、添加阅读全文按钮和分页等功能。

2.1 代码实现

使用以下代码自定义文章列表结构,可以根据需要包含或排除文章元素:

$args = array(
  'post_type' => 'post',
  'posts_per_page' => 10
);

// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {

  while ( $the_query->have_posts() ) {
    $the_query->the_post();

    // This is a single post
    echo '<article class="post">';

    // Post thumbnail
    if ( has_post_thumbnail() ) {
      // Thumbnail and link
      echo '<a href="' . get_permalink() . '">' . get_the_post_thumbnail() . '</a>';
    }

    // Post title and link
    echo '<h2><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>';

    // Post meta info
    echo '<div class="post-meta">';
    echo '<span class="date">' . get_the_date() . '</span>';
    echo '<span class="author">' . get_the_author() . '</span>';
    echo '<span class="comments">' . get_comments_number() . '</span>';
    echo '</div>';

    // Post content
    echo '<div class="post-content">' . get_the_excerpt() . '</div>';

    // A "read more" link
    echo '<a href="' . get_permalink() . '" class="read-more">Read More</a>';

    // End of the post
    echo '</article>';

  }

} else {
  // No posts found
}
/* Restore original Post Data */
wp_reset_postdata(); 

2.2 效果展示

自定义文章列表结构,添加了文章缩略图、元信息、摘要和“阅读更多”链接,使列表更具有视觉冲击力和可读性。

结束

本文简单介绍了WordPress中置顶文章和文章列表结构控制功能的使用方法。在实际使用中,可以根据需要进一步优化和定制。

阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228

大家谈论
    我的见解
    目录