如何使用jquery在wordpress中获取当前页面ID

use*_*743 6 wordpress jquery

如何单独使用 jquery 在 wordpress 中获取页面 id。我打算使用自定义脚本更改页面的某些样式,我需要知道页面 id。

Abh*_*hik 6

使用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');
Run Code Online (Sandbox Code Playgroud)

您可以通过这种方式在脚本中使用变量。

<script type="text/javascript">
    var MyPostID = MyScriptVars.postID;
</script>
Run Code Online (Sandbox Code Playgroud)


Diy*_*ang 6

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;
}
Run Code Online (Sandbox Code Playgroud)

将此函数添加到您的代码中。您现在可以使用以下方法获取页面 ID:

var id = get_current_page_id();
Run Code Online (Sandbox Code Playgroud)


Wim*_*ans 0

最好的方法是通过 PHP 添加全局 javascript 变量。

为此,首先将以下脚本添加到 page.php 模板文件中:

<script>
var pageId = <?php echo isset($posts[0]) ? $posts[0]->ID : 'null'; ?>;
</script>
Run Code Online (Sandbox Code Playgroud)

现在,在您的 javascript 代码中,您可以像这样使用这个全局变量。

<script>
if(pageId !== undefined && pageId) {
 // do some code based on pageId
}
</script>
Run Code Online (Sandbox Code Playgroud)

您可以使用相同的技术在 javascript 中使用其他 WordPress 变量。