2016-09-30 56 views
1

我想在WordPress中更新the_content_rss以便它适合feedburner。它需要找到每个img标签,看它是否有宽度和高度设置。如果它们大于600,它们应该减少到600.如果它们没有设置,那么宽度应该设置为600.我想使用一些代码here来做到这一点,但我有点卡住了,我会感激帮助修复它。在Wordpress Feed中调整img标签的大小

问题:

  1. 是否行得通?
  2. 它如何找到如果宽度为空 - 在哪种情况下添加它?

    <?php 
    function feedburner_img_resize($the_content) { 
    // Create a new istance of DOMDocument 
    $post = new DOMDocument(); 
    // Load $the_content as HTML 
    $post->loadHTML($the_content); 
    // Look up for all the <img> tags. 
    $imgs = $post->getElementsByTagName('img'); 
    
    // Iteration time 
    foreach($imgs as $img) {  
    
        // if width is smaller than 600 - no need to continue 
        $width = $img->getAttribute('width'); 
        if($width < 600) continue; 
    
        $img->removeAttribute('width'); 
        $img->setAttribute('width', 600); 
        $img->removeAttribute('height'); // so the image is not distorted 
    }; 
    
    return $post->saveHTML(); 
    } 
    
    add_filter('the_content_rss', 'feedburner_img_resize'); 
    ?> 
    
+0

考虑使用javascript? –

+0

我需要改变它使用PHP为了更新add_filter ... –

+0

我不是很熟悉wordpress,但你可以做一个ajax请求,然后将它传递到PHP和add_filter() –

回答

1

在function.php添加以下功能:

function aq_resize($url,$width,$height=null,$crop=null,$single=true){ 
    $up_info=wp_upload_dir(); 
    $up_dir=$up_info['basedir']; 
    $up_url=$up_info['baseurl']; 
    if (strpos($url,home_url()) === false){return false;} 
    $rel_path = str_replace($up_url, '', $url); 
    $img_path = $up_dir . $rel_path; 
    if (!file_exists($img_path) OR ! getimagesize($img_path)){return false;} 
    $info = pathinfo($img_path); 
    $ext = $info['extension']; 
    list($orig_w,$orig_h) = getimagesize($img_path); 
    $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop); 
    $dst_w = $dims['4']; 
    $dst_h = $dims['5']; 
    $suffix="{$dst_w}x{$dst_h}"; 
    $dstrel=str_replace('.'.$ext,'',$rel_path); 
    $dest="{$up_dir}{$dstrel}-{$suffix}.{$ext}"; 
    if($width >= $orig_w) { 
     if(!$dst_h) : 
      $img_url=$url; 
      $dst_w=$orig_w; 
      $dst_h=$orig_h; 

     else : 
      if(file_exists($dest) && getimagesize($dest)) { 
       $img_url="{$up_url}{$dstrel}-{$suffix}.{$ext}"; 
      } 
      else { 
       $resized=resize_image($img_path,$width,$height,$crop); 
       $resized_rel=str_replace($up_dir,'',$resized); 
       $img_url=$up_url.$resized_rel; 
      } 
     endif; 
    } 
    elseif(file_exists($dest) && getimagesize($dest)) { 
     $img_url="{$up_url}{$dstrel}-{$suffix}.{$ext}"; 
    } 
    else { 
     $resized=resize_image($img_path,$width,$height,$crop); 
     $resized_rel=str_replace($up_dir,'',$resized); 
     $img_url=$up_url.$resized_rel; 
    } 

    if($single) { 
     $image = $img_url; 
    } else { 
     $image = array (
      0 => $img_url, 
      1 => $dst_w, 
      2 => $dst_h 
     ); 
    } 
    return $image; 
} 

在一个地方需要总结的微缩模型,编写以下,对适合你的改变缩略图的大小:

<img src="<?php echo aq_resize(first_img(),180,130,true)?>