Change title tag dynamically or within plugin?

I have created a WP plugin which uses the query string to pull in page data based on what the visitor has selected. Obviously this ‘simulates’ additional pages but the page title does not change from the title set in WP Admin.

I have been trying to hook into wp_title to change the title tag on fly but can’t get this one working.

The following function works:

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

As soon as I try to pass a variable to it, it fails.

public function custom_title($title, $new_title) {
    return $new_title;
}

WordPress complains it’s missing the 2nd argument, I guess this makes sense since the function is being called at page load… I was hoping I could do something like $this->custom_title($title, 'new title); within my plugin but it doesn’t look like that is going to be possible?

I have posted this here because I think it’s a general PHP class issue.

Can I globalise a returned variable, e.g. I want to return the ‘title’ column from a query in another function such as $query->title

When the function runs it returns data from the database

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

I now need $query->title to be set as the page title.

public function custom_title()
{
  if($query->title)
  {
    $new_title = $query->title;
  }
}

A stripped down version of my class:

class FB_Events {
  private static $_instance = null;
  private $wpdb;
  public $_token;
  public $file;
  public $dir;
  public $assets_dir;
  public $assets_url;
  private $message;

  public function __construct($file="", $version = '1.0.0')
  {
    global $wpdb;
    $this->db = $wpdb;
    $this->fb_events_table = $this->db->prefix . 'fb_events';

    $this->_version = $version;
    $this->_token = 'fb_events';
    $this->_db_version = '1.0.0';

    $this->file = $file;
    $this->dir = dirname($this->file);
    $this->assets_dir = trailingslashit($this->dir) . 'assets';
    $this->assets_url = esc_url(trailingslashit(plugins_url('/assets/', $this->file)));

    register_activation_hook($this->file, array($this, 'install'));

    add_action('admin_menu', array($this, 'admin_menu'));
    add_action('init', array($this, 'rewrite_rules'), 10, 0);

    add_filter('query_vars', array($this, 'event_query_var'), 0, 1);

    // Add shortcodes for html output
    add_shortcode('fb_events_form', array($this, 'add_event_public'));
    add_shortcode('fb_events_display', array($this, 'view_events'));
    add_shortcode('fb_events_featured', array($this, 'featured_events'));
  }

  /**
   * Register rewrite rules
   * @access  public
   * @since   1.0.0
   * @return  void
   */
  public function rewrite_rules()
  {
    add_rewrite_rule('^events/add/?', 'index.php?pagename=events/add', 'top');
    add_rewrite_rule('^events/([^/]*)/?','index.php?pagename=events&event=$matches[1]', 'top');    
  }

  /**
   * Register event query string
   * @access  public
   * @since   1.0.0
   * @return  void
   */
  public function event_query_var($vars)
  {
    $vars[] = 'event';
    return $vars;
  }

  /**
   * View events from public website
   * @access  public
   * @since   1.0.0
   * @return  void
   */
  public function view_events()
  {
    $event = get_query_var('event');

    if(isset($event) && $event != '')
    {
      if($event != 'add')
      {
        $event = $this->db->get_row(
          $this->db->prepare("
            SELECT e.*, u.display_name AS username
            FROM {$this->fb_events_table} AS e
            LEFT JOIN {$this->db->prefix}users AS u
            ON e.user_id = u.id
            WHERE e.slug = %s
          ", $event)
        );

        if($event > 0)
        {
          /**
           * *********************************
           * NEED TO SET <title> to $event->name
           * *********************************
           */
          ob_start();

          if(isset($event->active) && $event->active == 0)
          {
            //error
          }
          else
          {
            //show the event
          }
        }
        else
        {
          // event does not exist error
        }
      }
    }
  }

  /**
   * Main FB_Events Instance
   * @since 1.0.0
   * @static
   * @return Main FB_Events instance
   */
  public static function instance($file="", $version = '1.0.0') {
    if(is_null(self::$_instance))
    {
      self::$_instance = new self($file, $version);
    }
    return self::$_instance;
  }

}

3 Answers
3

As of WP 4.4, wp_title is deprecated. If you simply need to override your title tag, pre_get_document_title is the filter you want to use.

add_filter( 'pre_get_document_title', 'generate_custom_title', 10 );

and the function would look something like this

function generate_custom_title($title) {
/* your code to generate the new title and assign the $title var to it... */
return $title;  
}

If you’re a stickler you’ll know that pre_get_document_title doesn’t normally take any args; but if you use the Yoast SEO plugin, you’ll find out that this function doesn’t do anything! So I also hook the ‘wpseo_title’ filter onto this same function.

add_filter( 'wpseo_title', 'generate_custom_title'), 15 );

just in case Yoast is turned on. Code reuse.

Leave a Comment