在我的wordpress页面中,我有从其他网站获取内容的帖子。到我的网页我只添加网页的网址和网页显示元从这个网址。
功能示例:
function getOGimage() {
$url = get_field('link');
$page_content = file_get_contents($url);
$dom_obj = new DOMDocument();
@$dom_obj->loadHTML($page_content);
$meta_val = null;
foreach($dom_obj->getElementsByTagName('meta') as $meta) {
if($meta->getAttribute('property')=='og:image'){
$meta_val = $meta->getAttribute('content');
}
}
echo '<img src="'.$meta_val.'" style="width:180px; height:auto;" />';}
我的循环:
<?php if ($popularindex->have_posts()) : ?>
<?php while ($popularindex->have_posts()) : $popularindex->the_post(); ?>
<li class="box" id="post-<?php the_ID(); ?>">
<div class="thumb-box">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
} else $OG_image = getOGimage();
?>
</a>
</div>
</li>
<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>
它可以工作,但会减慢页面速度。有人有办法吗?
我想保存这个元到数据库,但我不知道如何从主url自动做到这一点
先谢谢你
1条答案
按热度按时间qzlgjiam1#
最好不要使用
file_get_contents()
每次你需要渲染帖子的时候。除了速度慢,这意味着如果有200个用户访问这个页面,你将下载图像200次。wordpress有一个操作,您可以在每次在后端创建或更新帖子时将其挂接:
save_post
(您可以在此处找到更多详细信息:https://codex.wordpress.org/plugin_api/action_reference/save_post). 您应该钩住这些操作,并且每次创建/更新post时,您都会获取图像并将其保存到数据库中作为post_meta
. 您需要添加类似于以下内容的内容:那么当你的循环应该是如下所示:
我正在使用
get_field
以及update_field
自从你用过get_field
在你的问题上。我认为您正在使用acf插件来管理元数据。get_post_meta
以及update_post_meta
如果您不打算使用acf插件,则可以使用。