Is there any way to get yoast title inside page using their variable ( i.e. %%title%%)

Hasan Tareq picture Hasan Tareq · Dec 28, 2016 · Viewed 11.6k times · Source

I need to create a function so that I can use that inside any page which is outside the wordpress regular page. I mean wp_head() will not be placed there. I need it for a purpose.

The purpose is for amp(ampproject.org) page where I can't use any css or js. That's why I need this. I need to place a function at wp title so that the yoast title be placed there.

I need something like this:

function yoastVariableToTitle($variable){
    return yoast_vaialble_to_show_title($variable);
}

Answer

Raunak Gupta picture Raunak Gupta · Dec 28, 2016

By Default Yoast takes a format as %%title%% %%page%% %%sep%% %%sitename%%, and stores in wp_postmeta table under _yoast_wpseo_title key.

To only get Title of the page/post:

function yoastVariableToTitle($post_id) {
    $yoast_title = get_post_meta($post_id, '_yoast_wpseo_title', true);
    $title = strstr($yoast_title, '%%', true);
    if (empty($title)) {
        $title = get_the_title($post_id);
    }
    return $title;
}

There can be 2 possibility with SEO title

Case I: Admin enters %%title%% %%page%% %%sep%% %%sitename%% in SEO title field then the above code will return Post/Page default title.

Case II: Admin enters My Custom Title %%page%% %%sep%% %%sitename%% in SEO title field then the above code will return My Custom Title.


To get the full Meta Title of the page/post:

function yoastVariableToTitle($post_id) {

    $yoast_title = get_post_meta($post_id, '_yoast_wpseo_title', true);
    $title = strstr($yoast_title, '%%', true);
    if (empty($title)) {
        $title = get_the_title($post_id);
    }
    $wpseo_titles = get_option('wpseo_titles');

    $sep_options = WPSEO_Option_Titles::get_instance()->get_separator_options();
    if (isset($wpseo_titles['separator']) && isset($sep_options[$wpseo_titles['separator']])) {
        $sep = $sep_options[$wpseo_titles['separator']];
    } else {
        $sep = '-'; //setting default separator if Admin didn't set it from backed
    }

    $site_title = get_bloginfo('name');

    $meta_title = $title . ' ' . $sep . ' ' . $site_title;

    return $meta_title;
}

Hope this helps!