WordPress函数get_adjacent_post()获取相邻文章

WordPress函数get_adjacent_post()获取相邻文章

WordPress函数get_adjacent_post()获取相邻文章

  在 WordPress CMS内容管理系统中,get_adjacent_post是一个内置函数,用于检索与数据库中当前帖子相关的下一篇或上一篇帖子。

  推荐:如何更改WordPress时区

get_adjacent_post()函数基本语法

描述

  检索相邻的帖子。可以是下一篇或上一篇文章。

用法

<?php get_adjacent_post( $in_same_term, $excluded_terms, $previous, $taxonomy ) ?>

参数

  $in_same_term

  ( bool ) ( 可选) 帖子是否应该在同一个分类术语中。默认值:false

  $excluded_terms

 (int[]|string)(可选)排除的术语 ID 的数组或逗号分隔列表。默认值: ”

  $previous

  (bool)(可选)是否检索以前的帖子。如果为false,则返回下一篇文章的信息。默认值:true

  $taxonomy

  (string)(可选)分类法名称,如果 $in_same_term 为真。默认值:“category”

返回值

  • 如果成功,则发布对象。
  • 如果未设置全局$post,则为空。
  • 如果不存在相应的帖子,则为空字符串。

  推荐:如何修复WordPress后台响应速度慢

get_adjacent_post()函数示例

  链接到同一分类中的上一篇文章,文本标题为文章标题。(源文件可参考这里

<?php $prev_post = get_adjacent_post( true, '', true, 'taxonomy_slug' ); ?>
 <?php if ( is_a( $prev_post, 'WP_Post' ) ) { ?>
 	<a href="<?php echo get_permalink( $prev_post->ID ); ?>"><?php echo get_the_title( $prev_post->ID ); ?></a>
 <?php } ?>

  链接到同一分类中的下一篇文章,文章标题为文本。

<?php $next_post = get_adjacent_post( true, '', false, 'taxonomy_slug' ); ?>
 <?php if ( is_a( $next_post, 'WP_Post' ) ) {  ?>
 	<a href="<?php echo get_permalink( $next_post->ID ); ?>"><?php echo get_the_title( $next_post->ID ); ?></a>
 <?php } ?>

  显示下一篇文章的摘录

<?php
$next_post = get_adjacent_post( true, ”, false, ‘category’ );
if ( !empty( $next_post ) ):
$post_id = $next_post->ID;
$excerpt = get_post( $post_id, ”, ” ); ?>
<a href=”<?php echo $next_post->guid; ?>”><?php echo $excerpt->post_title; ?></a>
<?php echo $excerpt->post_excerpt; ?>
<?php endif; ?>

  推荐:如何隐藏WordPress登录页面

get_adjacent_post添加到functions.php文件

  将函数get_adjacent_post添加到 functions.php文件的示例:

function my_custom_adjacent_post_link() {
    $previous_post = get_adjacent_post(false, '', true);
    $next_post = get_adjacent_post(false, '', false);

    if (!empty($previous_post)) {
        echo '<a href="' . get_permalink($previous_post->ID) . '">Previous Post: ' . $previous_post->post_title . '</a>';
    }

    if (!empty($next_post)) {
        echo '<a href="' . get_permalink($next_post->ID) . '">Next Post: ' . $next_post->post_title . '</a>';
    }
}

add_action('my_custom_adjacent_post_link', 'my_custom_adjacent_post_link');

get_adjacent_post()函数过滤器

get_{$adjacent}_post_excluded_terms
get_{$adjacent}_post_join
get_{$adjacent}_post_sort
get_{$adjacent}_post_where

  推荐:WooCommerce Dropshipping免费下载WordPress Dropshipping插件

  推荐:WordPress函数使用手册

给文章评分

晓得博客,版权所有丨如未注明,均为原创
晓得博客 » WordPress函数get_adjacent_post()获取相邻文章

转载请保留链接:https://www.pythonthree.com/wordpress-get-adjacent-post/

Claude、Netflix、Midjourney、Chatgpt Plus账号购买,ChatGPT API购买,优惠码XDBK,用户购买的时候输入优惠码可以打95折

Chatgpt-Plus注册购买共享账号
滚动至顶部