出于某种原因atitle
属性未附加到next_post_link
和prev_post_link
在WordPress中调用。如何添加一个?
如何将标题属性添加到下一个和上一个帖子链接函数?
4 个回复
最合适的回答,由SO网友:kaiser 整理而成
更新当我删除GitHub上的回购协议时,这里有一个新的答案。
add_filter( \'previous_post_link\', \'wpse13044_adjacent_post_link_tooltip\', 10, 2 );
add_filter( \'next_post_link\', \'wpse13044_adjacent_post_link_tooltip\', 10, 2 );
function wpse13044_adjacent_post_link_tooltip( $format, $link )
{
$previous = \'previous_post_link\' === current_filter();
// Get the next/previous post object
$post = get_adjacent_post(
false
,\'\'
,$previous
);
// Copypasta from cores `get_adjacent_post_link()` fn
\'\' === $title = get_the_title( $post->ID );
AND $title = $previous
? sprint( __( \'Previous Post: %s\', \'your_textdomain\' ), $title )
: sprint( __( \'Next Post: %s\', \'your_textdomain\' ), $title );
$format = str_replace(
\'rel="\'
,sprintf(
\'title="%s" rel="\'
,$title
)
,$format
);
return "<span class=\'some classes\'>{$format}</span>";
}
SO网友:Rahman Sharif
不需要函数和过滤器,只需使用get_adjacent_post
而不是next_post_link
和prev_post_link
, 请注意get_adjacent_post
用于获取上一篇和下一篇文章,您可以阅读here要获取上一篇文章及其标题属性,请使用
$prev_post = get_adjacent_post(false, \'\', true);
if(!empty($prev_post)) {
echo \'<a href="\' . get_permalink($prev_post->ID) . \'" title="\' . $prev_post->post_title . \'">\' . $prev_post->post_title . \'</a>\'; }
要获取下一篇文章及其标题属性,请使用$next_post = get_adjacent_post(false, \'\', false);
if(!empty($next_post)) {
echo \'<a href="\' . get_permalink($next_post->ID) . \'" title="\' . $next_post->post_title . \'">\' . $next_post->post_title . \'</a>\'; }
SO网友:Picard102
我现在也在尝试这样做。过滤器功能似乎是最好的选择。
这就是我现在所处的位置,但我似乎无法获取下一篇或上一篇文章的标题并将其传递给过滤器。
编辑:找到了。可能有点骇客,但它起作用了。
add_filter(\'next_post_link\',\'add_title_to_next_post_link\');
function add_title_to_next_post_link($link) {
global $post;
$post = get_post($post_id);
$next_post = get_next_post();
$title = $next_post->post_title;
$link = str_replace("rel=", " title=\'".$title."\' rel", $link);
return $link;
}
add_filter(\'previous_post_link\',\'add_title_to_previous_post_link\');
function add_title_to_previous_post_link($link) {
global $post;
$post = get_post($post_id);
$previous_post = get_previous_post();
$title = $previous_post->post_title;
$link = str_replace("rel=", " title=\'".$title."\' rel", $link);
return $link;
}
SO网友:Ivan Shim
代码缩短了一点。
/*
* Add "title=" to previous_post_link and next_post_link
*/
add_filter(\'next_post_link\', function($link) {
$next_post = get_next_post();
$title = $next_post->post_title;
$link = str_replace(\'href=\', \'title="\'.$title.\'" href=\', $link);
return $link;
});
add_filter(\'previous_post_link\', function($link) {
$previous_post = get_previous_post();
$title = $previous_post->post_title;
$link = str_replace(\'href=\', \'title="\'.$title.\'" href=\', $link);
return $link;
});
结束