Yoast Metadata API to adjust/override the meta description

I wanted to use the following function to override the Yoast meta description:

add_filter('wpseo_metadesc','custom_meta');
function custom_meta( $desc ){

    if (/* do your test here to check template or any other values*/) {
        $desc = Change the description;
    } 

    return $desc;
}

However, Yoast SEO support recommends the Metadata API.

From this page, I understand I can use the wpseo_metadesc filter to adjust the Meta_Description_Presenter, but I am unsure how it is done; I am not a programmer.

I'd love some assistance to create some functions.php code that will grab the first 160 characters of the content if the meta description hasn't been set already.

Help appreciated. Steve

Topic plugin-wp-seo-yoast Wordpress

Category Web


I think you're on the right track here. You can use the wpseo_metadesc filter to alter the meta description any way you want. Check out below code, maybe it'll help you with your function.

add_filter( 'wpseo_metadesc', 'my_custom_meta_description' );
function my_custom_meta_description($description) {
    if ( !$description || empty($description) ) {
        global $post;
        $content = get_the_content($post->ID);
        if ( $content && !empty($content) ) {
            $description = substr($content, 0, 160);
        }
    }
    return $description;
}

I haven't tested the function so you may need to customize it for your need.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.