WordPress中通过短代码调用函数时如何获取单篇文章ID
在短代码调用的PHP函数中获取文章ID的几种方法
直接调用全局
$post对象
只要短代码是在文章内容里(循环内部)调用,直接用全局$post就能拿到ID:function my_custom_shortcode() { global $post; $post_id = $post->ID; // 这里可编写业务逻辑,比如返回ID或做其他处理 return "当前文章ID:" . $post_id; } add_shortcode('get_post_id', 'my_custom_shortcode');注意:如果短代码在循环外(比如侧边栏、自定义模板非循环区域)调用,
$post可能不是目标文章,需换其他方法。使用
get_the_ID()函数
这个函数专门返回当前循环内的文章ID,代码更简洁,效果和全局$post一致:function my_custom_shortcode() { $post_id = get_the_ID(); return "当前文章ID:" . $post_id; } add_shortcode('get_post_id', 'my_custom_shortcode');处理短代码不在循环内的场景
如果短代码要在文章之外使用(比如自定义页面模板、侧边栏),可以给短代码加参数手动指定文章ID:function my_custom_shortcode($atts) { // 设置默认值,无传参时用当前页面ID(若存在) $atts = shortcode_atts( array( 'id' => get_the_ID() ), $atts ); $post_id = $atts['id']; return "指定的文章ID:" . $post_id; } add_shortcode('get_post_id', 'my_custom_shortcode');使用时直接传ID:
[get_post_id id="123"]用
get_queried_object_id()获取当前查询的文章ID
如果当前页面本身是单篇文章页面,不管短代码在不在循环里,这个方法都能拿到页面对应的文章ID:function my_custom_shortcode() { $post_id = get_queried_object_id(); return "当前页面的文章ID:" . $post_id; } add_shortcode('get_post_id', 'my_custom_shortcode');
内容的提问来源于stack exchange,提问作者kawsar Ahmed
相关产品推荐
相关产品推荐

