WordPress核心中有什么内置的东西,可以让我从“固定链接结构”选项中获得相对路径吗?

时间:2021-02-13 作者:dewd

我担心我将不得不编写一堆代码来获得我需要的东西,这很好,但我想在开始这段旅程之前检查一下是否有任何内置的东西。

我正在开发一个插件,我需要获取给定插件的相对路径permalink_structure. 当前,permalink结构选项返回/%postname%/%post_id%/. 我有帖子(页面)id,例如100。

根据permalink的设置,我知道完整的相对路径应该是/iamapost/100. 然而,似乎我能做的最好的事情是:

get_permalink($post_id) === "https://example.com/iamapost/";
parse_url(get_permalink($post_id), PHP_URL_PATH) === "/iamapost/";
get_post_permalink($post_id) === "https://example.com/?post_type=page&p=100";
get_site_uri  === "https://example.com";
鉴于:

get_option(\'permalink_structure\') === "/%postname%/%post_id%/";
相对路径是否可以从此permalink设置页上设置的permalink结构或任何permalink结构中获取-无论是什么。。。

permalink settings page

Please, please do not assume this is a duplicate, because I really have searched and no question and answer is specific to reacting to whatever the permalink structure is at the time. If such an answer exists, then cool.

1 个回复
最合适的回答,由SO网友:Tom J Nowell 整理而成

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:

enter image description here

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> 

相关推荐

Problem with permalinks

我已经更改了类别的基本名称,现在它是“博客”,工作正常。但当我通过/blog/%category%/%postname%/更改结构时。显示404。如果我删除结构中的blog,它会再次工作,但我想使用blog word。问题出在哪里?非常感谢。