1

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;
  }

}
4
  • Please post all of the relevant bits of your class. With the code chopped up like that I can't tell what is supposed to happen.
    – s_ha_dum
    Jul 16, 2015 at 13:37
  • I'm not really sure how to elaborate? I have a function returning a set of results... one of which is $query->title .. I then need to be able to pass this to another function so that I can set it as the title in WP.
    – Goodbytes
    Jul 16, 2015 at 18:03
  • Well, did you post the class so that the relationships between its parts and WordPress can be analyzed?
    – s_ha_dum
    Jul 16, 2015 at 18:17
  • I have added my class but stripped out all of the unimportant bits.
    – Goodbytes
    Jul 16, 2015 at 21:02

3 Answers 3

6

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.

2
  • If I make the $title="hard coded"; Then I am able to return "hard coded". How about making the $title=$variable? I've tried to call the function generate_custom_title($title) inside the function but it seems not working.
    – Sam San
    Nov 4, 2017 at 18:10
  • Typo in the last add_filter. For priority 15 should be: add_filter( 'wpseo_title', 'generate_custom_title', 15 );
    – James0r
    Aug 3 at 6:45
2

I think your original problem was the variable scope. If you want a variable to be "seen" inside a php function, you must declare it "global" inside that function. This is working for me:

$new_title = 'this is my title';

function generate_custom_title($title) {
    global $new_title;
    $title = $new_title;
    return $title;  
    }

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

get_header();
0

I believe you can alter that with a filter on wp_title but you don't provide enough detail about your project to really get a good answer.

There is sample code in the Codex: https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_title

2
  • Thanks, does add_theme_support('title-tag') just call wp_title() ? I believe they modified the way it works so that it is easy to work with but not much information is provided at the moment. I'll test this at some point today, thanks
    – Goodbytes
    Jul 13, 2015 at 7:21
  • I have provided more details about what I am trying to do.
    – Goodbytes
    Jul 16, 2015 at 11:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.