get_the_ID()获取当前文章ID

目录

描述

Retrieve the numeric ID of the current post. This tag must be within The Loop.

get_the_ID() 描述

用法

 <?php get_the_ID(); ?> 

get_the_ID() 用法

参数

This tag has no parameters.

get_the_ID() 参数

示例

Store the ID

The ID can be stored as a variable using

 <?php $postid get_the_ID(); ?> 

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

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
<?php
$id = get_the_ID();
$dropdown = "<select name='dropdown-".$id."' >";
$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

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
<?php
echo '<input type="hidden" name="activepost" id="activepost" value="'.get_the_ID().'" />';
?>

If the ID is not called within the_loop, then we can use the_ID rather than echo get_the_ID();

get_the_ID() 示例

历史

添加于 版本: 2.1.0

get_the_ID() 历史

源文件

get_the_ID() 函数的代码位于 wp-includes/post-template.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Retrieve the ID of the current item in the WordPress Loop.
 *
 * @since 2.1.0
 *
 * @return int|false The ID of the current item in the WordPress Loop. False if $post is not set.
 */
function get_the_ID() {
	$post = get_post();
	return ! empty( $post ) ? $post->ID : false;
}

get_the_ID() 源文件

相关