简体   繁体   English

WordPress的字数统计,以排除短代码?

[英]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] 例如排除[shortcode][This Shortcode]

Any idea on how I could add that part to the above function? 关于如何将该部分添加到上述功能的任何想法吗?

WordPress has a handy function, strip_shortcodes. WordPress有一个方便的功能,strip_shortcodes。 Codex details here: https://codex.wordpress.org/Function_Reference/strip_shortcodes 此处的Codex详细信息: https : //codex.wordpress.org/Function_Reference/strip_shortcodes

Your function uses $post->ID but you aren't getting the global post value. 您的函数使用$post->ID但没有获得全局的post值。

Finally you already have access to the post content inside the global $post object so just use that instead of get_post_field. 最后,您已经可以访问全局$ post对象内部的帖子内容,因此只需使用它代替get_post_field。

Eg global $post; 例如, 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 ) ) );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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