Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

ACF field to be used in Yoast SEO title WordPress

  • SOLVED

Currently my post titles are:
Post Title - Site Title

I would like to use the ACF custom field 'social_title' if it is present, so it would look like:
social_title - Site Title

I have tried to do this in my functions using the hook wpseo_title. However I do not know how to add the Site Title in, and also an 'if else' statement.

add_filter('wpseo_title', 'add_to_page_titles');

function add_to_page_titles($title) {
$title = get_field( 'social_title', $post->ID );
return $title;
}


Can you help me correct my code?

P.s. Not all posts will have a social_title so an if else statement might be needed?

Answers (2)

2019-08-22

Hariprasad Vijayan answers:

Hello Ross,

Following code returns Site Title.
get_bloginfo( 'name' ).
So the code would be like this

add_filter('wpseo_title', 'add_to_page_titles', 10, 1);
function add_to_page_titles($title) {
global $post;
if(get_field( 'social_title', $post->ID )){
$title = get_field( 'social_title', $post->ID ). ' - '.get_bloginfo( 'name' );
}
return $title;
}

I have written condition, so it only affect if the post have ACF custom field.

Let me know if need help.

Kind Regards,
Hariprasad

2019-08-22

Fahad Murtaza answers:

Please try

Udpated: Refactored and better code formatting.


add_filter( 'wpseo_title', 'add_to_page_titles' );

function add_to_page_titles($title) {
global $post;
return get_field( 'social_title', $post->ID ) ? get_field( 'social_title', $post->ID ) : $title;
}