如何检查我的短代码回调是否正在解析摘录?

时间:2014-09-10 03:41:16

标签: wordpress

我正在编写一个短代码插件,但如果它将用于摘录,我不想返回任何输出。如何检查是否在摘录/非完整帖子上下文中调用它?

我发现discussion出于语义原因,is_excerpt()被拒绝,但在other places中也找不到更多线索。

也许短代码插件也应该传递给bool is_excerpt ......

编辑:基于note

  

“<! - more - > quicktag要求模板使用the_content()   而使用摘录需要并允许模板编写者   明确选择是否显示完整帖子(使用the_content())   或摘录(使用the_excerpt())。“

这意味着首选解决方案必须能够考虑这两个功能,例如,如果没有显示完整帖子,[myshortcode]应返回空字符串。

2 个答案:

答案 0 :(得分:0)

ScribuHakrethat ticket所说的内容几乎就是全部。前者是WP核心开发者,后者是SO强国...

可以做的是过滤摘录并删除短代码。如果它是一个简单的自封闭短代码[example],但如果不是[example id="foo"][example]content[/example],则需要一些heavy Regex,这很容易。

一个简单的过滤器:

add_filter( 'get_the_excerpt', function( $excerpt ) 
{
    return str_replace( '[myshortcode]', '', $excerpt );
});

答案 1 :(得分:0)

这样的事情应该有效。这有点骇人听闻,但我无法想到区分分页内容和完整内容:

add_filter('the_content', 'mm_selective_shortcode');
function mm_selective_shortcode($content){
    global $pages;
    if(count($pages) > 1)) remove_filter('the_content', 'do_shortcode');
    return $content;
}

问题是您实际上没有检查摘录。您正在检查内容(由the_content调用)以及是否已使用<!--more--> quicktag分解了该内容。由于Wordpress本身并不区分这两种显示方法,因此难以确保短代码在两者之间的呈现方式不同。

话虽如此,如果该内容已经分页,这将删除给定内容上的所有短代码。如果您只想定位自己的短代码,请尝试使用此代码:

add_filter('the_content', 'mm_selective_shortcode');
function mm_selective_shortcode($content){
    global $pages;
    if(count($pages) > 1)) remove_shortcode('myshortcode');
    return $content;
}

此代码尚未经过测试,因此我无法保证它可以直接使用。但它至少应该帮助你开始。