【发布时间】:2013-08-23 05:27:25
【问题描述】:
如何单独使用 jquery 在 wordpress 中获取页面 id。我计划使用我需要知道页面 id 的自定义脚本来更改页面的某些样式。
【问题讨论】:
如何单独使用 jquery 在 wordpress 中获取页面 id。我计划使用我需要知道页面 id 的自定义脚本来更改页面的某些样式。
【问题讨论】:
function get_current_page_id() {
var page_body = $('body.page');
var id = 0;
if(page_body) {
var classList = page_body.attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item.indexOf('page-id') >= 0) {
var item_arr = item.split('-');
id = item_arr[item_arr.length -1];
return false;
}
});
}
return id;
}
将此函数添加到您的代码中。 您现在可以使用以下方法获取页面 ID:
var id = get_current_page_id();
【讨论】:
使用wp_localize_script。
function my_custom_vars() {
global $wp_query;
$vars = array(
'postID' => $wp_query->post->ID,
);
wp_localize_script( 'myvars', 'MyScriptVars', $vars );
}
add_action ('wp_enqueue_scripts', 'my_custom_vars');
您可以通过这种方式在脚本中使用变量..
<script type="text/javascript">
var MyPostID = MyScriptVars.postID;
</script>
【讨论】:
如果您想单独在 jQuery 中获取当前页面 id,您可以通过以下步骤进行:
c_pageid和值get_the_ID();
var pageId=$("#c_pageid").val();
这可能会解决您的问题。
【讨论】:
$(document).ready(function() {
if ($("body").hasClass("page-id-3202")) {
// code here
}
});
【讨论】:
最好的方法是通过 PHP 添加全局 javascript 变量。
为此,首先将以下脚本添加到您的 page.php 模板文件中:
<script>
var pageId = <?php echo isset($posts[0]) ? $posts[0]->ID : 'null'; ?>;
</script>
现在在您的 javascript 代码中,您可以像这样使用这个全局变量。
<script>
if(pageId !== undefined && pageId) {
// do some code based on pageId
}
</script>
您可以使用相同的技术在 javascript 中使用其他 WordPress 变量。
【讨论】:
var pageId="<?php echo get_the_ID(); ?>"
在您的脚本中使用上述行
【讨论】:
var current_page_id = get_current_page_id();
function get_current_page_id() {
var page_body = $('body.page');
var page_id = '';
if(page_body) {
var classList = page_body.attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item.indexOf('page-id') >= 0) {
page_id = item;
return false;
}
});
}
return page_id;
}
【讨论】: