Wordpress - How can I add title attributes to next and previous post link functions?
Update
As I deleted the Repo on GitHub, here's a new answer.
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>";
}
No need for functions and filters all you need to do is to use get_adjacent_post
instead of next_post_link
and prev_post_link
, Note that get_adjacent_post
is used to get previous and next post, you can read about it here
To get previous post and it's title attribute use this
$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>'; }
To get next post and it's title attribute use this
$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>'; }
I'm trying to do this right now as well. The filter function seems like the best bet.
This is where I'm at now, but I can't seem to get the title of the next or previous post and pass it to the filter.
Edit: Figured it out. A bit hackey probably, but it works.
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;
}