Skip to content

Instantly share code, notes, and snippets.

@amarinediary
Last active January 22, 2022 23:04
Show Gist options
  • Save amarinediary/32b26bd5c26ecc846822ba1f1cf5ff5f to your computer and use it in GitHub Desktop.
Save amarinediary/32b26bd5c26ecc846822ba1f1cf5ff5f to your computer and use it in GitHub Desktop.
Retrieves the current permalink (WordPress, Woocommerce)
<?php
/**
* Retrieves the current permalink.
* Filters-out unregistered query variables through WordPress core get_query_var() function.
* Make it safe to use in database queries, redirects and HTTP requests through WordPress core esc_url_raw() function.
*
* @param String $args['relative'] (true|false), Relative path if true. Default to false.
*
* @return String Relative or absolute path to the current permalink.
*
* @since 1.0.0
*
* @see https://stackoverflow.com/a/70809779/3645650
*/
if ( ! function_exists( 'wpso_50761584' ) ) {
function wpso_50761584( $args = array() ) {
$args = empty( $args ) ? array(
'relative' => false,
) : $args;
global $wp;
parse_str( $_SERVER['QUERY_STRING'], $variables );
$buffer = array();
foreach ( $variables as $variable => $value ) {
if ( get_query_var( $variable ) )
array_push( $buffer, array( $variable => $value ) );
};
$buffer = array_reduce( $buffer, 'array_merge', array() );
$permalink = $args['relative'] ? wp_make_link_relative( esc_url_raw( add_query_arg( $buffer, home_url( $wp->request ) ) ) ) : esc_url_raw( add_query_arg( $buffer, home_url( $wp->request ) ) );
return $permalink;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment