设置wp_title来更改插件中的标题标签?

Goo*_*tes 7 php wordpress class title

我创建了一个WP插件,它使用查询字符串根据访问者选择的内容提取页面数据.显然,这会'模拟'其他页面,但页面标题不会改变WP Admin中的标题集.

我一直试图wp_title在飞行中改变标题标签,但不能使这个工作.

以下功能有效:

public function custom_title($title) {
    return 'new title';
}
add_filter( 'wp_title', array($this, 'custom_title'), 20 );
// changes <title> to 'new title'
Run Code Online (Sandbox Code Playgroud)

一旦我尝试将变量传递给它,它就会失败.

public function custom_title($title, $new_title) {
    return $new_title;
}
Run Code Online (Sandbox Code Playgroud)

WordPress抱怨它缺少第二个参数,我想这是有道理的,因为函数是在页面加载时被调用的...我希望我可以$this->custom_title($title, 'new title);在我的插件中做一些事情,但它看起来不会那样可能吗?

我在这里发布了这个,因为我认为这是一个普通的PHP类问题.

我可以全局化返回的变量,例如,我想从另一个函数中返回查询中的"标题"列,例如 $query->title

函数运行时,它返回数据库中的数据

public function view_content()
{
  $query = $this->db->get_row('SELECT title FROM ...');
  $query->title; 
}
Run Code Online (Sandbox Code Playgroud)

我现在需要将$ query-> title设置为页面标题.

public function custom_title()
{
  if($query->title)
  {
    $new_title = $query->title;
  }
}
Run Code Online (Sandbox Code Playgroud)

emb*_*emb 6

看起来您可能误解了过滤机制的工作原理.A filter是WordPress在特定时间使用某些参数调用的函数,并检索结果.以下是对WordPress过滤器的一个不错的介绍:http://dev.themeblvd.com/tutorial/filters/

您可能还想wp_title特别查看过滤器的文档页面,以便了解您的函数应该期望的参数:https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_title

执行您想要的代码看起来像这样:

public function __construct() {
    //...
    add_filter( 'wp_title', array($this, 'custom_title'), 20);
}

public function view_content() {

    $query = $this->db->get_row('SELECT title FROM ...');
    $this->page_title = $query->title; 
}

public function custom_title($title) {

    if ($this->page_title) {
        return $this->page_title;
    }

    return $title;
}
Run Code Online (Sandbox Code Playgroud)