【问题标题】:Dynamically modify Wordpress post attachment img URLs using PHP使用 PHP 动态修改 Wordpress 发布附件图片 URL
【发布时间】:2018-01-18 10:14:06
【问题描述】:
是否可以修改当前帖子的图片附件的URL,以便浏览器接收到带有img标签中修改过的URL的html?
我不想更新图片附件属性。
我正在寻找与帖子内容相同的灵活性,因为它可以读取、修改然后返回帖子的 the_content。
我知道 wp_get_attachment_image_src() 和 the_post_thumbnail_url() 是获取附件 URL 的方法。但是我找不到任何方法可以为当前帖子返回修改后的 URL。
一种可能性是use output buffering to catch the final HTML,使用ob_start()等
但是有没有更有针对性的方法来解析帖子图片附件?
【问题讨论】:
标签:
php
wordpress
image
post
thumbnails
【解决方案1】:
我已经使用输出缓冲回答了我自己的问题。请注意,我使用的是 Genesis 主题,因此可以访问其他钩子,例如 genesis_after_content,它位于循环之后和页脚之前,因此已经准备好完整的 html 内容。这可以访问特色图像 URL(无法从 get_the_content 获得)以及来自特色页面/帖子小部件的任何/所有图像 URL 等......无论您在呈现的内容中看到什么。
<?php
//at start of php script set output buffering
ob_start();
session_start();
//script does stuff
if (isset($_SESSION['some_variable_is_set'])) {
add_action( 'genesis_after_content', 'my_replace_image_urls');
//used genesis_after_content hook as full html content is now prepared
}
function my_replace_image_urls() {
$full_content = ob_get_clean();
//modify $full_content as needed
echo $full_content;
}