wordpress循环中的函数减慢页面速度

Function in wordpress loop slow down the page

在我的 wordpress 页面中,我有从其他网站获取内容的帖子。在我的页面中,我只添加了页面的 url,并且页面显示了来自此 url.

的元数据

函数示例:

    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

提前致谢

理想情况下,您不会在每次需要渲染 post 时都使用 file_get_contents()。除了速度慢之外,这意味着如果 200 个用户访问该页面,您将下载图像 200 次。

WordPress 有一个操作,每次在后端创建或更新 post 时,您都可以挂钩它:save_post(您可以在此处找到更多详细信息:https://codex.wordpress.org/Plugin_API/Action_Reference/save_post) .您应该挂钩这些操作,每次 post 是 created/updated 时,您获取图像并将其作为 post_meta 保存到数据库中。您需要添加类似于以下内容的内容:

function post_updated_set_og_image( $post_id ) {

    $url = get_field('link', $post_id);
    $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');
    }
    update_field('og_image_src', $meta_val, $post_id);

}
add_action( 'save_post', 'post_updated_set_og_image' );

然后你的循环应该是这样的:

<?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 = get_field('og_image_src');
                  echo '<img src="'.$og_image.'" style="width:180px; height:auto;" />';
                }
                ?>
                </a>
            </div>
        </li>
    <?php endwhile; ?>
<?php else : ?> 
<?php endif; ?>

我正在使用 get_fieldupdate_field,因为您在问题中使用了 get_field。我认为您正在使用 ACF 插件来管理元数据。如果您不打算使用 ACF 插件,可以使用 get_post_metaupdate_post_meta