Is there anything built into the WordPress core to enable me to get the relative path from the “permalink structure” option
No, because it isn\'t necessary, PHP provides this via parse_url
. Using php -a
we can launch an interactive PHP shell and test the code:
php > echo parse_url( \'http://example.com/iamapost/100\', PHP_URL_PATH );
/iamapost/100
php >
If we read the PHP docs we see that it also handles query strings, etc, e.g.:
php > echo parse_url( \'http://example.com/iamapost/100?foo=bar#test\', PHP_URL_PATH );
/iamapost/100
php >
Your problem is not retrieving the relative URL.
Your results do not contain the /100
because your permalinks do not contain it. Run echo get_permalink();
and it will become obvious. You are assuming that your permalinks contain the post ID. They do not.
Given that:
get_option(\'permalink_structure\') === "/%postname%/%post_id%/";
Can the relative path be taken from this or any permalink structure set up on the permalink settings page - whatever that might be...
Yes, via get_permalink()
and parse_url
.
I decided to spin up a local site of WP v5.6.1, and gave it the permalink structure you used:
I then fired up wp shell
and ran the code and got the expected results:
vagrant@vvv:/srv/www/wordpress-one/public_html$ wp shell
wp> echo parse_url(get_permalink(168), PHP_URL_PATH);
/test-2/168/
wp> echo get_option(\'permalink_structure\');
/%postname%/%post_id%/
wp>