PHP - 如何将 `<?php the_content(); ?>` 转化为字符串或者获取它的字符串形式

6

我经常使用这个函数:

get_search_query() 

为了获得搜索返回的值并能够修改和使用字符串。

我需要知道一个将<?php the_content(); ?>作为字符串获取的函数,或者如何将该函数返回的内容转换为字符串。

内容只是带有段落标签的简单单词,但使用该函数后我也会得到标签,我想只获取文本以便将其添加到超链接中。

6个回答

11

6
虽然这可能是最好的方法,但请注意 get_the_content() 并不仅仅是将内容返回而非打印出来的 the_content()。一个重要的区别是 get_the_content() 不会过滤内容。例如,如果您使用短代码嵌入视频、联系表单等内容,则默认情况下它们将无法正常工作。您还需要在内容上运行 apply_filters("the_content", ...) 。更多信息请参考 WP Codex:https://codex.wordpress.org/Function_Reference/the_content#Alternative_Usage - rinogo

5
如果您需要在变量中存储带有HTML格式的内容,请执行以下操作:
apply_filters('the_content',$post->post_content)

2
不了解WP,但暗示的命名约定表明使用get_the_content()。通过进一步搜索发现有一个变体get_the_content_with_formatting
另一种选择是将the_content()包装在ob_start()ob_get_contents()+ob_end()中。后者返回此时为止进行的任何print输出。

2
您应该使用get_the_content()函数将其转换为字符串,然后可以进行格式化处理。

0
$the_post = get_post();
$the_post->post_content;

您可以使用此方法获取的所有内容列表:

[ID] =>
    [post_author] =>
    [post_date] => 
    [post_date_gmt] => 
    [post_content] => 
    [post_title] => 
    [post_excerpt] => 
    [post_status] =>
    [comment_status] =>
    [ping_status] => 
    [post_password] => 
    [post_name] =>
    [to_ping] => 
    [pinged] => 
    [post_modified] => 
    [post_modified_gmt] =>
    [post_content_filtered] => 
    [post_parent] => 
    [guid] => 
    [menu_order] =>
    [post_type] =>
    [post_mime_type] => 
    [comment_count] =>
    [filter] =>

0
请注意,get_the_content 不返回与 the_content 显示的内容相同的内容。要获取相同的内容,您需要执行以下操作:
$content = apply_filters('the_content', get_the_content());

echo $content;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接