Wordpress - Get current URL (permalink) without /page/{pagenum}/

You can get the current URL through home_url( $wp->request ).

Try the example below:

global $wp;

// get current url with query string.
$current_url =  home_url( $wp->request ); 

// get the position where '/page.. ' text start.
$pos = strpos($current_url , '/page');

// remove string from the specific postion
$finalurl = substr($current_url,0,$pos);


echo $finalurl;

Answer by Govind Kumar worked, however, it only returned the URL if /page/{pagenum}/ was present in the URL and returned nothing if not. I needed a universal solution that will always return the base URL without pagination, so I modified Govind's code a bit and wrapped into a function:

function get_nopaging_url() {

    global $wp;

    $current_url =  home_url( $wp->request );
    $position = strpos( $current_url , '/page' );
    $nopaging_url = ( $position ) ? substr( $current_url, 0, $position ) : $current_url;

    return trailingslashit( $nopaging_url );

}

echo get_nopaging_url();

Now, it always returns correct URL.

(This is useful if you need to implement some kind of post filters that add a param to filter posts by, let's say, a meta filed. So, even if a user sets the filter param on page X, the new filtered results will always start from the base URL, not page X and throwing 404 if there's less filtered posts.)


Actually the easiest would be to use get_pagenum_link() which will return you the current URL without any /page/* paramaters.


Bonus

You can also simply use it to build "Previous" and "Next" links dynamically using the 'paged' query variable:

// Get the current page number.
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$first_page = '<a href="' . get_pagenum_link() . '" class="page-first"><<</a>';
$prev_page = '<a href="' . get_pagenum_link($paged - 1) . '" class="page-prev"><</a>';
$next_page = '<a href="' . get_pagenum_link($paged + 1) . ' class="page-next">></a>';

// And having a `WP_Query` object you can also build the link for the last page:
$max = $the_query->max_num_pages;
$last_page = '<a href="' . get_pagenum_link($max) . '" class="page-last">>></a>';