get_the_ID()
云策文档标注
概述
get_the_ID() 函数用于在 WordPress Loop 中检索当前项目的 ID。它返回整数类型的 ID,若 $post 未设置则返回 false。
关键要点
- 函数返回当前 WordPress Loop 中项目的 ID,类型为 int 或 false。
- 内部实现基于 get_post() 函数,检查 $post 对象是否存在并返回其 ID。
- 在博客首页使用时,可能返回第一个文章的 ID 而非首页 ID。
- 在 Loop 外部或需要条件检查时,建议使用 get_queried_object_id() 或其他条件标签。
- 可用于生成唯一锚点标识符,例如在动态菜单或表单中。
代码示例
// 基本用法:获取当前文章 ID
$post_id = get_the_ID();
// 在 Loop 外部获取 ID 的示例
global $post;
$post_id = ( empty( $post->ID ) ) ? get_the_ID() : $post->ID;
// 使用 get_queried_object_id() 替代
$postID = get_queried_object_id();注意事项
- 确保在 WordPress Loop 内调用以获取正确的当前项目 ID。
- 对于自定义文章类型或不确定环境时,可结合 global $post 使用。
- 避免在需要首页 ID 时误用,应使用 is_home() 等条件标签。
原文内容
Retrieves the ID of the current item in the WordPress Loop.
Source
function get_the_ID() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
$post = get_post();
return ! empty( $post ) ? $post->ID : false;
}
Changelog
| Version | Description |
|---|---|
| 2.1.0 | Introduced. |
Skip to note 6 content
Craigbavender
Should be noted that if this is ran on the Blog homepage, it instead returns the first listed Post ID instead of the blog homepage ID.
Skip to note 7 content
Joy Chetry
In some cases, such as when you’re outside The Loop, you may need to use
get_queried_object_id() instead of get_the_ID() .
Skip to note 8 content
Codex
Post Anchor Identifier
get_the_ID()can be used to provide a unique anchor in a script. For instance, a dynamically-generated drop down menu with actions for each post in an archive could have"; $dropdown .= "<option id='option1-". $id ."'>Option 1</option>"; $dropdown .= "</select>"; ?>This would allow us to use JavaScript to control the element as it has a unique ID, and when submitting it as a form through the POST or GET methods the dropdown box will be sent with a unique ID which allows the script to note which post it is working on. Alternatively a hidden variable could be sent which will allow the script to see which post the submission is referring to
Skip to note 9 content
tradesouthwest
If you are working with custom post types or you are just not sure if the file you are working in has any direct access to the post, you can try this handy statement to get the ID of a post; outside of the loop even.
global $post; $post_id = ( empty( $post->ID ) ) ? get_the_ID() : $post->ID;Then use $post_id string to assure you have the post ID. Example usage:
if ( get_post_type( $post_id ) != 'wpbdp_listing' ) return;Skip to note 10 content
Codex
Store the ID
The ID can be stored as a variable using