【问题标题】:Create 2 Wordpress Post Type Templates创建 2 个 Wordpress 帖子类型模板
【发布时间】:2014-11-13 12:51:52
【问题描述】:

我为我的帖子类型制作了一个模板,效果很好。但是,我希望对原件的某些部分进行类似的复制。

我有一个使用 jQuery $.get 的 ajax 调用,我想定位第二个帖子类型模板以仅将 html 拉入当前页面。

此时,ajax 调用会加载包括脚本在内的整个页面。 Modernizr 会像整个内容一样被加载。

我尝试过使用查询变量,如下所示:

// http://scratch99.com/wordpress/development/how-to-change-post-template-via-url-parameter/

function sjc_add_query_vars($vars) {
    return array('template') + $vars;
}
add_filter('query_vars', 'sjc_add_query_vars');

function sjc_template($template) {
  global $wp;
  if ($wp->query_vars['template'] === 'test') {
    return dirname( __FILE__ ) . '/single-test.php';
  }
  else {
    return $template;
  }
}
add_filter('single_template', 'sjc_template');

代码运行良好,但出现此错误

Notice: Undefined index: template in /wp-content/themes/custom--theme/functions.php on line 262

262 is: f ($wp->query_vars):

当正常加载项目单时,我认为这是代码遇到 else 语句时的问题。

任何帮助都会很棒。

【问题讨论】:

  • 这是因为此时$wp 没有像template 这样的键。让我们var_dump($wp); 调试,template 键在哪里。
  • @lolka_bolka 我不确定解决方法是什么,我知道调试已打开,但我想在关闭它之前对其进行排序..
  • 然后试试这个:if (isset($wp->query_vars['template']) && $wp->query_vars['template'] === 'test') {
  • 工作得很好,其次你能解释一下你写的代码,这样我就可以理解它了。其次你能不能把它作为答案,所以我可以检查一下!
  • 我已将其添加为答案并尝试解释。

标签: php wordpress custom-post-type query-variables


【解决方案1】:

您收到此错误,因为您的 $wp->query_vars 不存在,或者如果它存在,(比它实际上是一个数组)template 键不存在。我所做的是检查整个$wp->query_vars['template'] 是否存在于PHP isset() 函数中:

From PHP documentation:
isset — Determine if a variable is set and is not NULL

阅读我的 cmets。这是我最好的解释。

function sjc_template($template) {
    //Now we have a $template variable with a value.

    //Get the $wp as a global variable
    global $wp;

    //This condition is check, is there an existing key in $wp->query_vars 
    //called template. If $wp->query_vars or $wp->query_vars['template'] not 
    //extists (the second can not exists if the first is not exists), 
    //then it will not check, what is the value is, instead of that just jump
    //to the second case to return $template;
    if (isset($wp->query_vars['template']) && $wp->query_vars['template'] === 'test') {
        //So at here, we have this: $wp->query_vars['template'] and the value of it is test
        return dirname(__FILE__) . '/single-test.php';
    } else {
        //In all other cases we return with the given parameter of function
        return $template;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多