如何使用jQuery获取WordPress当前文章ID?
解决方案
方法1:通过PHP将文章ID传递到JS(推荐)
这是WordPress场景下最可靠的方案,利用官方机制把PHP变量注入到JS环境中:
步骤1:在主题functions.php中添加代码
function enqueue_custom_scripts() { // 仅在单篇文章页面加载脚本 if (is_singular()) { global $post; // 注册并加载你的自定义JS文件 wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom.js', array('jquery'), '1.0', true); // 传递文章ID到JS wp_localize_script('custom-script', 'wpSiteData', array( 'postID' => $post->ID )); } } add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
步骤2:在JS脚本中调用
jQuery(function($) { $('#myCustomButton').click(function() { var attachementId = wpSiteData.postID; // 直接使用传递过来的文章ID }); });
如果不想用规范的wp_localize_script,也可以在页面模板里直接输出全局变量(快速但不够严谨):
<script> var currentPostID = <?php echo get_the_ID(); ?>; </script>
之后JS里直接用currentPostID即可。
方法2:从DOM元素中提取ID
很多WordPress主题会在<body>标签添加包含文章ID的类名(比如postid-123),可以通过JS解析获取:
jQuery(function($) { $('#myCustomButton').click(function() { // 从body类名中解析文章ID var postId = $('body').attr('class').match(/postid-(\d+)/)[1]; var attachementId = parseInt(postId, 10); // 转为数字类型 }); });
这种方法依赖主题的DOM结构,稳定性不如第一种,适合无法修改PHP代码的场景。
内容的提问来源于stack exchange,提问作者herrfischer
相关产品推荐
相关产品推荐

