简体   繁体   中英

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

i want the page id of current page in wordpress . i know get_the_ID() which is used to get the page id when Permalink Settings is Default . But in my case Permalink Settings is Post name and i want the page_id is it possible ? . 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. Wordpress loads the page or the post in a loop that's why when you run get_the_ID() it gaves you the 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.

get_the_ID() works anywhere no matter what the permalink structure is. 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. In that case, get_the_ID() will return the ID of the current post ID in that loop. 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 ..

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' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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