Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
Code to automatically generate meta tags in wordpress is not working properly

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
}


about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!