Customize the previous_post_link output

I am trying to customize the output of the previous post link.
I want to display 2 titles (with link) for the previous post, one should be a custom text and other should be title of post, for example:

Read Previous
This is Post tile.

Both of them should link to the previous post

Read More

I am trying following code, but it displays both titles as ‘Read Previous’.

<?php previous_post_link('

    <div class="prev-post">
        <span class="title1">
            <h5>%link</h5>
        </span>

        <span class="title2">
            <h5>%link</h5>
        </span>
    </div>

    ', __('Read Previous', 'domain')

    ); ?>

Related posts

2 comments

  1. I would just filter previous_post_link and next_post_link. This way, your template stays clean, and you move the extra logic to the functions.php.

    Example, not tested:

    add_filter( 'previous_post_link', 'filter_single_post_pagination', 10, 4 );
    add_filter( 'next_post_link',     'filter_single_post_pagination', 10, 4 );
    function filter_single_post_pagination( $output, $format, $link, $post )
    {
        $title = get_the_title( $post );
        $url   = get_permalink( $post->ID );
        $text  = 'Read previous';
        $class = 'prev-post';
        $rel   = 'prev';
    
        if ( 'next_post_link' === current_filter() )
        {
            $text  = 'Read next';
            $class = 'next-post';
            $rel   = 'next';
        }
        return "<div class='$class'>
                <div class='title1'>
                    <h5><a href='$url' rel='$rel'>$text</a></h5>
                </div>
                <div class='title2'>
                    <h5><a href='$url' rel='$rel'>$title</a></h5>
                </div>
            </div>";
    }
    
  2. Of course it is the same. Why would you think that that same placeholder– %link— would be replaced by different strings? Only one of which you’ve provided?

    The previous_posts_link() function is not meant to take multiple placeholders anyway. You aren’t going to be able to do this the way you are trying to.

    The simplest thing to do is pass the post title in the string:

    previous_post_link('
      <div class="prev-post">
          <span class="title1">
              <h5>%link</h5>
          </span>
          <span class="title2">
              <h5>'.get_the_title().'</h5>
          </span>
      </div>', 
      __('Read Previous', 'domain')
    );
    

    In fact, I don’t see a filter that would let you do it any other way.

Comments are closed.