全局页面ID变量为空错误

时间:2018-05-30 作者:richardev

我正在创建主题,我需要在主题中创建全局变量functions.php 文件

目前我是这样做的:

/**
 * Setup globals
 */
global $nb_id, $nb_page;

$nb_id = get_the_ID();
// Prepare & set fallback
$globals_array  = array(
    \'nb_id\'     => $nb_id,
    \'nb_page\'   => array(
        \'id\'    => $nb_id,
        \'end\'   => \'front\',
        \'name\'  => \'home\',
        \'type\'  => \'page\'
    )
);

// Set each value from globals array as global $var;
foreach ($globals_array as $name => $value) {
    global $$name;
    $$name              = $value;
    $_GLOBALS[$name]    = $value;

    // Set user view of page
    if($name == \'nb_page\'){
        if(is_admin()) $$name[\'end\']    = \'back\';
        $$name[\'name\']      = $nb_pagenow;
        // Determine if is page or single post
        if(is_single()) $$name[\'type\']  = \'single\';

        $_GLOBALS[$name]    = $$name;
    }
}
问题是我无法使用get_the_ID(), $wp_query->get_queried_object_id() 甚至$wp->public_query_vars 具有page_id.

当前所有场景都返回以下值:

  1. get_the_ID() = null
  2. $wp_query->get_queried_object_id() = 0
  3. $wp->public_query_vars = "page_id" [34]=> string(5) "error"functions.php!?

1 个回复
最合适的回答,由SO网友:richardev 整理而成

经过一些研究,感谢@Milo指出在wp 设置好了,我终于开始工作了。事实上,我必须尽快打电话wp 查询并生成了一些帖子/页面数据;

这是我的最终解决方案add_action( \'template_redirect\', \'nb_setup_globals\' );

以下是最终代码:

/**
 * Setup globals
 */
global $nb_id, $nb_view, $nb_page;
function nb_setup_globals(){
    global $post, $nb_id, $nb_view, $nb_page;

    // Set default vars for globals
    $nb_id = $post->ID;
    $nb_view        = \'front\';
    $nb_post_name   = \'index\';
    $nb_post_type   = \'post\';

    // Post type page
    if(is_page()){
        if(nb_get_template_slug()){
            $nb_post_name = nb_get_template_slug();
        }else{
            $nb_post_name = \'page\';
        }
        $nb_post_type = \'page\';
    }

    // Post type post / custom post
    if(is_single()){
        $nb_post_name = $post->post_type;
    }

    // View
    if(is_admin()) $nb_view = \'back\';

    // Before globals set default vars one last time
    $globals_array  = array(
        \'nb_page\'   => array(
            \'id\'    => $nb_id,
            \'name\'  => $nb_post_name,
            \'type\'  => $nb_post_type
        )
    );

    /**
     * Let the magin GLOBALS be registered
     */
    foreach ($globals_array as $name => $value) {
        global $$name;

        $$name = $value;
    }
}
add_action( \'template_redirect\', \'nb_setup_globals\' );
这也适用于后端(帖子/页面编辑等)。虽然还没有完全测试过。

结束

相关推荐

Organize functions.php

组织职能的最佳方式是什么。php的性能?我有几个add\\u操作调用、几个add\\u主题支持、几个add\\u过滤器和4个附加函数。对于面包屑、样式表、注册菜单和小部件。我们是否需要遵守订单?例如,首先是所有add\\u过滤器函数,然后是add theme\\u support等。不确定添加代码是否相关,因为这是一个一般性问题。如果需要,我很乐意更新这篇文章。