我需要获取当前帖子/页面的 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;
}
来自这里:how to get the current page id in wordpress using jquery
但据我了解,这仅适用于类型:“页面”。它给了我一些问题,我希望它也适用于“帖子”类型(也许是自定义类型的帖子,尽管我目前没有任何这些并且它不是很重要)。
我对此有点弱,所以任何人都可以将其转换为也可以用于帖子吗? (因此无论类型如何,它都应该返回 id )。
我认为这是在开始时从 $('body.page')
中删除 '.page' 的简单修复 - 但也许不是。任何帮助,将不胜感激。
最佳答案
此脚本正在抓取以 page-id
开头的正文元素类名段。只需使用 post-id
切换即可。
if (item.indexOf('post-id') >= 0) {
我验证了 the official WordPress blog 上存在这样的类值.要查找并处理这两种情况,请尝试以下操作:
$.each(classList, function (index, item) {
// check for page ID *or* post ID
if (item.indexOf('page-id') >= 0 || item.indexOf('post-id') >= 0) {
var item_arr = item.split('-');
id = item_arr[item_arr.length - 1];
return false;
}
});
关于javascript - 如何获取当前页面的 ID 或在 WordPress 中发帖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58202009/