Skip to content

Missing document_title_separator filter? #6400

@petenelson

Description

@petenelson

While working on a client site, I needed to implement a custom title tag for a page that has content that comes from an API (i.e. not a single post, archive, author, etc). Part of this implementation was creating the <title> tag for the header. Because of this, we implemented filters for the various WPSEO functions (meta, title tag, etc). While working on the wpseo_title filter and reading through core, I see it's not using the document_title_separator filter that core uses in _wp_render_title_tag(). Core uses this to render a title if you have title-tag enabled for theme, and it calls wp_get_document_title() to generate the title.

WPSEO is using the pre_get_document_title filter to generate the document title, but if it's not being used, further down in the core code is this:

$sep = apply_filters( 'document_title_separator', '-' );

Since WPSEO doesn't tap into the document_title_separator hook, it looks like the only way to get the configured title separator is to call the utils method directly, so I ended up implementing this:

add_filter( 'wpseo_title', __NAMESPACE__ . '\title_tag' );

/**
 * Filter hook for the head title tag.
 *
 * @param  string $title The title.
 * @return string
 */
function title_tag( $title ) {

	// Get the page title (comes from term meta via a custom function).
	$title = title( '' );

	// Get the title separator from WPSEO, or via the standard filter
	// used by core.
	if ( class_exists( '\WPSEO_Utils' ) ) {
		$sep = \WPSEO_Utils::get_title_separator();
	} else {
		$sep = apply_filters( 'document_title_separator', '-' );
	}

	// Get the site name.
	$site = get_bloginfo( 'name', 'display' );

	// Return the title and site for the head title tag.
	return esc_html( sprintf( '%1$s %2$s %3$s', $title, $sep, $site ) );
}

Not sure if this was by design or an oversight, and I know this is likely an edge-case, but it might be good to have a document_title_separator in WPSEO that returns the WPSEO_Utils::get_title_separator() instead of need to call it directly.

Technical info

  • WordPress version: 4.6
  • Yoast SEO version: 3.9

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions