php - Need to Echo A Url path to show on a wordpress page

admin2025-01-07  6

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

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

[url_path_number]

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]

Share Improve this question asked Dec 19, 2017 at 17:27 Glenn ThorntonGlenn Thornton 12 silver badges5 bronze badges 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 Commented Jan 3, 2018 at 7:37
Add a comment  | 

1 Answer 1

Reset to default 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); 
} );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736262124a793.html

最新回复(0)