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

pxy2qtax  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(296)

在我的wordpress页面中,我有从其他网站获取内容的帖子。到我的网页我只添加网页的网址和网页显示元从这个网址。
功能示例:

  1. function getOGimage() {
  2. $url = get_field('link');
  3. $page_content = file_get_contents($url);
  4. $dom_obj = new DOMDocument();
  5. @$dom_obj->loadHTML($page_content);
  6. $meta_val = null;
  7. foreach($dom_obj->getElementsByTagName('meta') as $meta) {
  8. if($meta->getAttribute('property')=='og:image'){
  9. $meta_val = $meta->getAttribute('content');
  10. }
  11. }
  12. echo '<img src="'.$meta_val.'" style="width:180px; height:auto;" />';}

我的循环:

  1. <?php if ($popularindex->have_posts()) : ?>
  2. <?php while ($popularindex->have_posts()) : $popularindex->the_post(); ?>
  3. <li class="box" id="post-<?php the_ID(); ?>">
  4. <div class="thumb-box">
  5. <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
  6. <?php if ( has_post_thumbnail() ) {
  7. the_post_thumbnail();
  8. } else $OG_image = getOGimage();
  9. ?>
  10. </a>
  11. </div>
  12. </li>
  13. <?php endwhile; ?>
  14. <?php else : ?>
  15. <?php endif; ?>

它可以工作,但会减慢页面速度。有人有办法吗?
我想保存这个元到数据库,但我不知道如何从主url自动做到这一点
先谢谢你

qzlgjiam

qzlgjiam1#

最好不要使用 file_get_contents() 每次你需要渲染帖子的时候。除了速度慢,这意味着如果有200个用户访问这个页面,你将下载图像200次。
wordpress有一个操作,您可以在每次在后端创建或更新帖子时将其挂接: save_post (您可以在此处找到更多详细信息:https://codex.wordpress.org/plugin_api/action_reference/save_post). 您应该钩住这些操作,并且每次创建/更新post时,您都会获取图像并将其保存到数据库中作为 post_meta . 您需要添加类似于以下内容的内容:

  1. function post_updated_set_og_image( $post_id ) {
  2. $url = get_field('link', $post_id);
  3. $page_content = file_get_contents($url);
  4. $dom_obj = new DOMDocument();
  5. @$dom_obj->loadHTML($page_content);
  6. $meta_val = null;
  7. foreach($dom_obj->getElementsByTagName('meta') as $meta) {
  8. if($meta->getAttribute('property')=='og:image'){
  9. $meta_val = $meta->getAttribute('content');
  10. }
  11. update_field('og_image_src', $meta_val, $post_id);
  12. }
  13. add_action( 'save_post', 'post_updated_set_og_image' );

那么当你的循环应该是如下所示:

  1. <?php if ($popularindex->have_posts()) : ?>
  2. <?php while ($popularindex->have_posts()) : $popularindex->the_post(); ?>
  3. <li class="box" id="post-<?php the_ID(); ?>">
  4. <div class="thumb-box">
  5. <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
  6. <?php if ( has_post_thumbnail() ) {
  7. the_post_thumbnail();
  8. } else{
  9. $og_image = get_field('og_image_src');
  10. echo '<img src="'.$og_image.'" style="width:180px; height:auto;" />';
  11. }
  12. ?>
  13. </a>
  14. </div>
  15. </li>
  16. <?php endwhile; ?>
  17. <?php else : ?>
  18. <?php endif; ?>

我正在使用 get_field 以及 update_field 自从你用过 get_field 在你的问题上。我认为您正在使用acf插件来管理元数据。 get_post_meta 以及 update_post_meta 如果您不打算使用acf插件,则可以使用。

展开查看全部

相关问题