Wordpress - different post title on frontend than

2019-09-21 11:44发布

问题:

I need to change Wordpress theme function.php file so it will show custom name for post on frontend which is different than the title in post editor/URL.

For instance: Post title in text editor/url is "New York" but on front end will be shown "New York - never sleeping city". The reason for this is to shorten URL to basic metadata and keep "fancy name" on frontend only (posts, archives, sitemap, search results...). For "fancy name" I would like to use SEO title from Yoast SEO plugin.

In my case the pages are based on Wordpress posts types. So I need to define somewhere pool of posts(pages) IDs which should not be affected. The best solution is also NOT to affect all descendant pages under listed IDs.

The question is how should I modify function.php file?

Note for community: if you see my question as not clear, please write comment before you will mark my question as off-topic so I can tune it and make it better.

回答1:

If I understand what you want correctly, you can place this code in the functions.php of your theme

function set_my_seo_title($title, $id)
{
    global $post;
    $seo_title=get_post_meta($id, '_yoast_wpseo_title', true);         
    return ((!empty($seo_title)&&$post->post_type=='post') ? $seo_title : $title);
}

add_filter('the_title', 'set_my_seo_title', 15, 2);

This will check if post got SEO title set. If yes, it will be used, if no - it will use regular post title.