我目前正在用WordPress 3.5开发一个网站,我需要检索Post Text (Only text, not include images) 在Archive Page. 我可以用wp_excerpt()
方法没有任何问题。但对我来说,主要的问题是我无法获得准确的文本布局。wp_excerpt()
方法返回忽略所有额外空格和换行符的文本。我该怎么办?我想我会Only Post Text with Exact Layout 如果我能从wp_content()
方法提前感谢您的帮助!
如何只从wp_content()检索文本,而不从wp_excerpt()检索文本?
甚至更简单:
echo wp_strip_all_tags( get_the_content() );
通过使用:get_the_content()
检索帖子内容。(必须在循环中使用)与
the_content()
是吗get_the_content()
不通过\'the_content
\'. 这意味着get_the_content()
不会自动嵌入视频或扩展短代码等。wp_strip_all_tags()
正确剥离所有HTML标记,包括脚本和样式。
本机WordPress函数无法仅检索文本,但您可以使用WordPress过滤器和regex代码来解决此特定问题。
要获取未匹配的文本,请使用get_the_content() function. 要应用所有过滤器,请以这种方式使用(请参阅法典:http://codex.wordpress.org/Function_Reference/the_content#Alternative_Usage ):
$content = get_the_content();
$content = apply_filters(\'the_content\', $content);
$content = str_replace(\']]>\', \']]>\', $content);
echo $content;
在应用过滤器之前,有一个空间供您自定义修改,例如删除图像。这样做:$content = get_the_content();
$content = preg_replace(\'/(<)([img])(\\w+)([^>]*>)/\', "", $content);
$content = apply_filters(\'the_content\', $content);
$content = str_replace(\']]>\', \']]>\', $content);
echo $content;
preg\\U replace代码的来源:http://www.phpzag.com/php-remove-image-tags-from-a-html-string-with-preg_replace/ 您可能还需要删除短代码(如果使用)。这也可以通过preg\\u replace完成,我打赌你会在谷歌上找到一些。
我结合了这篇文章中其他答案的结果来剥离图像和音频等,但保留了格式。首先使用get_the_content
, 然后通过“the\\u content”过滤器添加格式等,然后使用php的strip_tags
仅允许有限数量的标记。
strip_tags(apply_filters(\'the_content\',get_the_content()),"<p><a><br><b><u><i><strong><span><div>");
下面的代码非常适合我。只需将此添加到functions.php
主题中的文件:
// Hook : to get content without images
add_filter(\'the_content\', \'wpse_get_content_without_images\');
function wpse_get_content_without_images() {
$content = get_the_content();
$content = preg_replace( \'/<img[^>]+./\', \'\', $content );
echo $content;
}
然后,使用echo the_content();
.以下是删除库内容和仅包含内容的代码。
$content = get_the_content();
$content = preg_replace(\'/\\[gallery.*ids=.(.*).\\]/\', "", $content);
$content = apply_filters(\'the_content\', $content);
$content = str_replace(\']]>\', \']]>\', $content);
echo $content;