I need to automatically generate meta tags from content in wordpress, the problem is that the code that I found on many blogs while searching either uses $des_post = str_replace( array( "\\n", "\\r", "\\t" ), ' ', $des_post); or $des_post = str_replace( array( "\n", "\r", "\t" ), ' ', $des_post);, which offers a security flaw (XSS), not to mention that it doesn't always strip the html tags correctly, so I've modified the code as follows:
function gretathemes_meta_description() {
global $post;
if ( is_singular() ) {
$des_post = strip_tags( $post->post_content );
$des_post = strip_shortcodes( $post->post_content );
$des_post = esc_attr( $des_post );
$des_post = mb_substr( $des_post, 0, 300, 'utf8' );
print '<meta name="description" content="' . $des_post . '" />' . "\n";
}
if ( is_home() ) {
print '<meta name="description" content="' . get_bloginfo( "description" ) . '" />' . "\n";
}
if ( is_category() ) {
$des_cat = strip_tags(category_description());
print '<meta name="description" content="' . $des_cat . '" />' . "\n";
}
}
add_action( 'wp_head', 'gretathemes_meta_description');
function gretathemes_meta_tags() {
print '<meta name="meta_name" content="meta_value" />';
}
add_action('wp_head', 'gretathemes_meta_tags');
The problem is that now it doesn't remove the html tags, so I get a meta description like this while verifying with metatag checkers (seo tools):
<!-- wp:paragraph -->
<p>The description goes here.
The problem is that html code like <!-- wp:paragraph --><p> shouldn't show up.
The thing here is that the function esc_attr is getting the html code and copying, isn't there a way to get the rendered post's text instead? Or any other solution?
Use html purifier
in your theme's functions.php or plugin file:
require_once '/path/to/HTMLPurifier.auto.php';
function better_strip_tags($dirty_html){
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
return $purifier->purify($dirty_html);
}