Get the prev / next page links only (not title, etc)

Short answer: get_previous_posts_page_link is the function you want:

<?php if($url = get_previous_posts_page_link()): ?>
  do stuff with $url
<?php endif; ?>

Longer answer: follow the code.

previous_posts_link calls get_previous_posts_link.

<?php
/**
 * Display the previous posts page link.
 *
 * @since 0.71
 * @uses get_previous_posts_link()
 *
 * @param string $label Optional. Previous page link text.
 */
function previous_posts_link( $label = null ) {
    echo get_previous_posts_link( $label );
}

get_previous_posts_link calls previous_posts to fetch the link URI itself.

<?php
/**
 * Return the previous posts page link.
 *
 * @since 2.7.0
 *
 * @param string $label Optional. Previous page link text.
 * @return string|null
 */
function get_previous_posts_link( $label = null ) {
    global $paged;

    if ( null === $label )
        $label = __( '&laquo; Previous Page' );

    if ( !is_single() && $paged > 1 ) {
        $attr = apply_filters( 'previous_posts_link_attributes', '' );
        return '<a href="' . previous_posts( false ) . "\" $attr>". preg_replace( '/&([^#])(?![a-z]{1,8};)/i', '&#038;$1', $label ) .'</a>';
    }
}

previous_posts is just a little wrapper around the function you’re looking for: get_previous_posts_page_link

<?php
/**
 * Display or return the previous posts page link.
 *
 * @since 0.71
 *
 * @param boolean $echo Optional. Echo or return;
 */
function previous_posts( $echo = true ) {
    $output = esc_url( get_previous_posts_page_link() );

    if ( $echo )
        echo $output;
    else
        return $output;
}

The function we want:

<?php
/**
 * Retrieve previous posts page link.
 *
 * Will only return string, if not on a single page or post.
 *
 * Backported to 2.0.10 from 2.1.3.
 *
 * @since 2.0.10
 *
 * @return string|null
 */
function get_previous_posts_page_link() {
    global $paged;

    if ( !is_single() ) {
        $nextpage = intval($paged) - 1;
        if ( $nextpage < 1 )
            $nextpage = 1;
        return get_pagenum_link($nextpage);
    }
}

I included all of that to illustrate how you can go about finding answers by looking through the core. Tools like ack can help you get started:

shell$ cd /path/to/your/wordpress/install
shell$ ack "function previous_posts_link"

In general, the WordPress is pretty good at making sure a function only does one thing. Tracing from broader functions (ala previous_posts_link and other template tags) back to more basic functions is usually a good way to learn some cool stuff and find your answer.

Leave a Comment