简体   繁体   English

如果永久链接为帖子名称,如何在wordpress中获取页面ID

[英]how to get page id in wordpress if Permalink is Post name

i want the page id of current page in wordpress . 我想要wordpress中当前页面的页面ID。 i know get_the_ID() which is used to get the page id when Permalink Settings is Default . 我知道get_the_ID()用于在永久链接设置为Default时获取页面ID。 But in my case Permalink Settings is Post name and i want the page_id is it possible ? 但是在我的情况下,“永久链接设置”是“ 帖子名称” ,我想要page_id吗? . if yes then how ? 如果是,那怎么办?

Try This: 尝试这个:

 <?php
global $post;
echo "pageid: ".$post->ID;
?>

You can try this is you have page name 您可以尝试此操作,因为您拥有页面名称

function get_page_id($page_name){
    global $wpdb;
    $page_name = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$page_name."'");
    return $page_name;
}

get_the_ID() gives you the current ID of a post/page in a loop. get_the_ID()为您提供循环中帖子/页面的当前ID。 Wordpress loads the page or the post in a loop that's why when you run get_the_ID() it gaves you the ID. Wordpress在循环中加载页面或帖子,这就是为什么当您运行get_the_ID()时会给您ID。 Now that function has nothing to do with the permalinks. 现在,该功能与永久链接无关。 If you're not in any loop (for example you're trying to run that when wordpress is being initialized, you won't get the ID you're looking for because that part is not already set. 如果您不在任何循环中(例如,您正在尝试在初始化wordpress时运行该循环,那么您将不会得到想要的ID,因为该部分尚未设置。

get_the_ID() works anywhere no matter what the permalink structure is. 无论永久链接结构如何,get_the_ID()均可在任何地方使用。 The only case i noticed it gives you a result other than the current page or post is when you're already in a loop other that wordpress default's. 我注意到它给您除当前页面或帖子以外的结果的唯一情况是,当您已经处于除wordpress默认值之外的循环中时。 In that case, get_the_ID() will return the ID of the current post ID in that loop. 在这种情况下,get_the_ID()将返回该循环中当前帖子ID的ID。 You can learn more about the loops in the codex. 您可以了解有关编解码器中循环的更多信息。

Now if you're still lost, can you provide a sample of code where you're using that function and you don't get the result you're expecting? 现在,如果您仍然迷路,是否可以在使用该函数的地方提供代码示例,而不会得到预期的结果?

you can use get_page_by_title() if you really want .. 如果确实需要,可以使用get_page_by_title()

Full parameters are 完整参数为

get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' );

so use like this 所以这样使用

$custom_post = get_page_by_title( 'pagename', OBJECT, 'your_custom_post_type' );
$post   = get_page_by_title( 'pagename', OBJECT, 'post' );

and just to complete the answer, there is also the similar 只是为了完成答案,还有类似的

get_page_by_path()

$page = get_page_by_path( 'about/us' ); $ page = get_page_by_path('about / us');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM