简体   繁体   中英

Wordpress Word Count to exclude shortcodes?

I have a function that gets the overall word count within a post.

function ic_word_count() {
    global $post;

    $ic_content = strip_tags(  $post->post_content );
    $ic_stripped = strip_shortcodes($ic_content);
    return $ic_stripped;
}

I'm trying to get it to exclude all shortcodes, so basically exclude anything with square brackets and everything in between them. For example exclude [shortcode] or [This Shortcode]

Any idea on how I could add that part to the above function?

WordPress has a handy function, strip_shortcodes. Codex details here: https://codex.wordpress.org/Function_Reference/strip_shortcodes

Your function uses $post->ID but you aren't getting the global post value.

Finally you already have access to the post content inside the global $post object so just use that instead of get_post_field.

Eg global $post;

function ic_word_count() {
    global $post;

    $wc_content = $post->post_content;
    $ic_word_count = str_word_count( strip_tags( strip_shortcodes( $wc_content ) ) );

    return $ic_word_count;
}

A smaller version:

function ic_word_count() {
    global $post;

    return str_word_count( strip_tags( strip_shortcodes( $post->post_content ) ) );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM