Wordpress replace meta description

2020-03-30 05:02发布

I need to replace the existing <meta name="description"...> generated by wp_head() function in header.php with a custom meta description. The information in the page is not a regular wordpress post, is taken from an external DB. I was able to add my custom meta but the old one is also there

function add_meta_tags() 
{
    global $data;
    if(!is_null($data['metas']['page_meta_description']) )
    {
        echo '<meta name="description" content="'.$data['metas']['page_meta_description'].'">';
    }
}
add_action('wp_head', 'add_meta_tags');

Is there any way to: - delete the default meta description with an action or filter in function.php? or, - replace the value of meta description somehow before is rendered?

3条回答
萌系小妹纸
2楼-- · 2020-03-30 05:38

The Description Meta tag is generally handled by the template header (header.php) or by a Plugin that is adding the description to the site (Such as SEO Title Tag). Since you are getting a duplicate description, you should check for plugins that are outputting a description tag.

For other annoying meta tags and other things put in the header, you can use the remove_action() function in the functions.php file of your template to do this and can look at the documentation here: https://codex.wordpress.org/Function_Reference/remove_action

I do something similar for a WP site I run and needed to remove every single meta tag that goes into the head and here is the code that I have at the bottom of my functions.php file to do it:

// Remove Meta Tags that are Unneeded
remove_action('wp_head','feed_links_extra', 3);
remove_action('wp_head','rsd_link');
remove_action('wp_head','feed_links', 2);
remove_action('wp_head','wlwmanifest_link');
remove_action('wp_head','index_rel_link');
remove_action('wp_head','parent_post_rel_link', 10, 0);
remove_action('wp_head','start_post_rel_link', 10, 0);
remove_action('wp_head','adjacent_posts_rel_link', 10, 0);
remove_action('wp_head','noindex');
remove_action('wp_head','wp_generator');
remove_action('wp_head','rel_canonical');
remove_action('wp_head', 'wp_shortlink_wp_head');

Obviously, only use the ones you need! I had trouble finding a list of all the functions for the meta-tags so I wanted to include all of the ones I used.

查看更多
三岁会撩人
3楼-- · 2020-03-30 05:39

Install Yoast plugin, you will be able to generate meta tags by manually putting it as you want to show on search engine result page.

查看更多
时光不老,我们不散
4楼-- · 2020-03-30 05:40
    function remove_meta_descriptions($html) {
    $pattern = '/<meta name(.*)=(.*)"description"(.*)>/i';
    $html = preg_replace($pattern, '', $html);
    return $html;
}
function clean_meta_descriptions($html) {
    ob_start('remove_meta_descriptions');
}
add_action('get_header', 'clean_meta_descriptions', 100);
add_action('wp_footer', function(){ ob_end_flush(); }, 100);
查看更多
登录 后发表回答