0

I need to extract a url path number to a shortcode... Here is an example below...

https://example.com/page/c/1

I need the number "1" to be shown with a shortcode...

[url_path_number]

1
  • You get all values from an URL via $_REQUEST or $_GET. However I think this value integer is the ID of a post, page or similar in your WP install, so that you can use the WP core function like get_the_ID.
    – bueltge
    Jan 3, 2018 at 7:37

1 Answer 1

0

You can find that with somthing like the following

add_shortcode( 'url_path_number', function ( $atts ) {

    // use an attribute or the current URL
    $a = shortcode_atts( array(
        'url' => get_permalink(),
    ), $atts );

    // get the path from the URL
    $path = parse_url($a['url'],PHP_URL_PATH);
    $parts = array_filter(explode('/', $path),function($v) { return $v !== ''; });

    // get the last dir of path
    return end($parts); 
} );

Using the shortcode will return current URL

[url_path_number]

or you can specify the URL

[url_path_number url="https://example.com/page/c/1"]

UPDATE:

to go just after the path, and not use get_permalink()

add_shortcode( 'url_path_number', function ( $atts ) {
    $a = shortcode_atts( array(
        'path' => $_SERVER['REQUEST_URI'],
    ), $atts );
    $parts = array_filter(explode('/',$a['path']),function($v) { return $v !== ''; });
    return end($parts); 
} );
3
  • Is it possible to add this to the url instead of get_permalink... <?php $Path=$_SERVER['REQUEST_URI']; echo $URI='example.com'.$Path; ?> Dec 19, 2017 at 18:26
  • I've updated my answer to reflect going after just the path, without get_permalink() Dec 19, 2017 at 18:46
  • the update code is awfully insecure.. You should never use an input variable without validation, or at the minimum escape it when returning the result. Feb 21, 2018 at 6:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.