WordPress函数:get_adjacent_post_link 获取相邻(上一篇下一篇)文章链接

江河/ 2023年05月15日/ WordPress/ 浏览 836

函数原型:


get_adjacent_post_link( string $format, string $link, bool $in_same_term = false, int[]|string $excluded_terms = '', bool $previous = true, string $taxonomy = 'category' ): string


获取相邻(上一篇、下一篇)的文章。


参数说明:


$format,占位符 %link 表示整个 a 标签。比如:'%link ->',最后生成的结果类似:<a></a>->。


$link,a 标签内部内容。占位符 %title 表示文章标题。如果不使用 %title,生成的 a 标签里也就不会有文章标题了。


$in_same_term,是否要求是同一分类下的。


$previous,true 上一篇,false 下一篇。


$taxonomy,默认 'category',与 $in_same_term 配合使用。


返回结果:


当前文章的上一篇或下一篇文章。如果上一篇或下一篇文章不存在,则返回空字符串。


函数源码:


function get_adjacent_post_link( $format, $link, $in_same_term = false, $excluded_terms = '', $previous = true, $taxonomy = 'category' ) {
	if ( $previous && is_attachment() ) {
		$post = get_post( get_post()->post_parent );
	} else {
		$post = get_adjacent_post( $in_same_term, $excluded_terms, $previous, $taxonomy );
	}

	if ( ! $post ) {
		$output = '';
	} else {
		$title = $post->post_title;

		if ( empty( $post->post_title ) ) {
			$title = $previous ? __( 'Previous Post' ) : __( 'Next Post' );
		}

		/** This filter is documented in wp-includes/post-template.php */
		$title = apply_filters( 'the_title', $title, $post->ID );

		$date = mysql2date( get_option( 'date_format' ), $post->post_date );
		$rel  = $previous ? 'prev' : 'next';

		$string = '<a href="' . get_permalink( $post ) . '" rel="' . $rel . '">';
		$inlink = str_replace( '%title', $title, $link );
		$inlink = str_replace( '%date', $date, $inlink );
		$inlink = $string . $inlink . '</a>';

		$output = str_replace( '%link', $inlink, $format );
	}

	$adjacent = $previous ? 'previous' : 'next';

	return apply_filters( "{$adjacent}_post_link", $output, $format, $link, $post, $adjacent );
}


包含钩子:


apply_filters( 'the_title', string $post_title, int $post_id )

apply_filters( "{$adjacent}_post_link", string $output, string $format, string $link, WP_Post|string $post, string $adjacent )


发表评论

暂无评论,抢个沙发...

客服 工单