以编程方式将第一个图像设置为特色

时间:2014-01-27 作者:user2820604

我有400多个帖子,里面有图片,我有一个新模板,每个帖子都需要一个特色图片,这是我上一个模板不需要的。。。我想知道是否有一个脚本可以添加到我的函数中。php能够抓取每篇文章中的第一张图片,并将其设置为特色图片。。。到目前为止,我已经找到了这个,但它不起作用。。。

function auto_set_featured() {
global $post;
$has_thumb = has_post_thumbnail($post->ID);
if (!$has_thumb)  {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
    if ($attached_image) {
        foreach ($attached_image as $attachment_id => $attachment) {
            set_post_thumbnail($post->ID, $attachment_id);
        }
    }
}
}
add_action(\'the_post\', \'auto_set_featured\');
add_action(\'save_post\', \'auto_set_featured\');
add_action(\'draft_to_publish\', \'auto_set_featured\');
add_action(\'new_to_publish\', \'auto_set_featured\');
add_action(\'pending_to_publish\', \'auto_set_featured\');
add_action(\'future_to_publish\', \'auto_set_featured\');
这个脚本将适用于新帖子,但我需要它来影响我所有的旧帖子,有什么建议吗?

5 个回复
SO网友:gmazzap

关于你发布的代码,我想说一些事情:

您可以避免使用6种不同的操作,因为一种就足够了:\'save_post\' 每次创建或更新帖子时都会触发$post: \'save_post\' 将传递post id,您可以使用它。此外,准备函数以接收参数将帮助您以编程方式运行相同的函数。代码的编辑版本将变为:

function auto_set_featured( $post = NULL ) {
  // retrieve post object
  $post = get_post( $post ); 
  // nothing to do if no post, or post already has thumbnail
  if ( ! $post instanceof WP_Post || has_post_thumbnail( $post->ID ) )
     return;
  // prepare $thumbnail var
  $thumbnail = NULL;
  // retrieve all the images uploaded to the post
  $images    = get_posts( array(
    \'post_parent\'    => $post->ID,
    \'post_type\'      => \'attachment\',
    \'post_status\'    => \'inherit\',
    \'post_mime_type\' => \'image\',
    \'posts_per_page\' => 1
  ) );
  // if we got some images, save the first in $thumbnail var
  if ( is_array( $images ) && ! empty( $images ) )
     $thumbnail = reset( $images );
  // if $thumbnail var is valid, set as featured for the post
  if ( $thumbnail instanceof WP_Post )
     set_post_thumbnail( $post->ID, $thumbnail->ID );
}

add_action( \'save_post\', \'auto_set_featured\' );
现在,对于旧帖子,您唯一需要的就是通过查询检索它们,然后为每个帖子运行相同的函数。

只需注意只执行一次任务:这是一个非常重要的时间&;消耗资源的任务,因此应该只运行一次,可能在后端运行。

我会用transient 目的:

add_action( \'admin_init\', function() {

  if ( (int) get_transient(\' bulk_auto_set_featured\' ) > 0 )
     return;

  $posts = get_posts( \'posts_per_page=-1\' ) ;
  if ( empty( $posts ) )
    return;

  array_walk( $posts, \'auto_set_featured\' );

  set_transient( \'bulk_auto_set_featured\', 1 );
});
将此代码添加到functions.php 或者到插件,登录后端,准备等待几秒钟,然后仪表板才会出现,但在那之后,所有帖子都应该有缩略图,至少每个上传了图像的帖子都应该有缩略图。

如果一切正常,您可以删除最后一个代码段,只保留第一个。

注意我的代码需要php 5.3+

SO网友:Brad Dalton

在子主题函数文件中使用此代码regenerate thumbnails

function wpsites_auto_set_featured_image() {
      global $post;
      $featured_image_exists = has_post_thumbnail($post->ID);
          if (!$featured_image_exists)  {
          $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
                      if ($attached_image) {
                            foreach ($attached_image as $attachment_id => $attachment) {
                            set_post_thumbnail($post->ID, $attachment_id);
                            }
                       }
                    }
  }
add_action(\'the_post\', \'wpsites_auto_set_featured_image\');

SO网友:r_alex_hall

“”Set All First Images As Featured“为我工作。

只要进行一次黑客攻击,它就可以逆转这一操作。

Easy Add Thumbnail 也可以做到这一点Quick Featured Images 我想我在搜索时看到了另一个插件。

SO网友:hs777it

Simple Function Code

 //Set First Image as FeaturedImage
add_action(\'add_attachment\', \'set_first_as_featured\');
add_action(\'edit_attachment\', \'set_first_as_featured\');
function set_first_as_featured($attachment_ID)
  {
   $post_ID = get_post($attachment_ID)->post_parent;
   if (!has_post_thumbnail($post_ID)) {
    set_post_thumbnail($post_ID, $attachment_ID);
  }
}
SO网友:sergiolovillo

我不得不开发相同的功能。就我而言,我必须根据一个帖子类别设置特色图片。

这里有必须插入当前主题模板中的代码。必须调用此模板,例如:“页面集图像”。php’(如果需要,您可以获得有关如何创建页面模板的更多信息here):

<?php

/* In the URL of the page \'set-images\', put as parameter \'setting = 1\' to
   set, as featured image of the posts of the category entered that do not
   have featured image, the first image shown in each post. */

echo \'In the URL of the page put as parameter "setting = 1" to set,
as a featured image of the posts of the category entered that do not have
featured image, the first image shown in each post.\';

$setting = isset($_GET[\'setting\']) ? $_GET[\'setting\'] : \'\';

if($setting == 1){
    get_posts_by_category();
}


/**
 * We get all the posts in a category. To enter the category, you have to change 
 * the value of the key \'category-name\' by the corresponding slug.
 * 
 * @author Sergio Lovillo
 * @return bool
 */

function get_posts_by_category():bool{

    $args = array(
        \'posts_per_page\' => \'-1\',
        \'category_name\' => \'category-slug\'
    );
    $posts = get_posts($args);

    if(isset($posts) && !empty($posts)){
        get_posts_first_image($posts);
    }
    return true;
}


/**
 * We check if each post in the category entered has a featured image; If the 
 * post doesn\'t have it, we get the URL of the first image shown in the post.
 * 
 * @author Sergio Lovillo
 * @param array $posts
 * Array containing all posts in the category entered
 * @return bool
 */

function get_posts_first_image(array $posts):bool{

    $posts_without_thumbnail = 0;
    $changed_posts_total = 0;

    foreach($posts as $post){

        $featured_image_exists = has_post_thumbnail($post->ID);

        if(isset($featured_image_exists) && empty($featured_image_exists)){

            $posts_without_thumbnail++;            
            $doc = new DOMDocument();
            $doc->loadHTML(apply_filters(\'the_content\', $post->post_content));
            $xpath = new DOMXPath($doc);
            $src = $xpath->evaluate("string(//img/@src)");

            if(isset($src) && !empty($src)){
                $res = set_posts_featured_images($src, $post->ID);
            } 
            if($res){
                $changed_posts_total++;
            }         
        }
    }
    echo \'<br />---<br />Total posts: \' . count($posts) . \'.<br />Posts without 
    featured image: \' . $posts_without_thumbnail . \'.<br />Total modified 
    posts:\' . $changed_posts_total . \'.\';
    return true;   
}

/**
 * We remove the width and height of the URL of the first image shown in the 
 * post. Then we get the ID of the image based on its URL. Finally, we set the 
 * first image displayed in the post as its featured image, using the post ID 
 * and the image ID.
 * 
 * @author Sergio Lovillo
 * @param string $firs_image_url
 * String that contains the URL of the first image shown in the post.
 * @param int $post_id
 * Post ID.
 * @return bool
 */

function set_posts_featured_images(string $first_image_url, int $post_id):bool{
            
    $first_image_formatted_url = preg_replace(\'/-\\d+x\\d+(?=\\.[a-z]{3,4}$)/i\', \'\', $first_image_url);
    $first_image_url_id = attachment_url_to_postid($first_image_formatted_url);
    $res = false;
    $featured_image_total = 0;

    if(isset($first_image_url_id) && !empty($first_image_url_id)){
        $res = set_post_thumbnail($post_id, $first_image_url_id);
    }
    return $res;
}

?>
同样,在我的示例中,您必须发布一个带有此slug的页面:“设置图像”。发布页面后,您必须在浏览器上转到该页面并添加为参数“setting=1”。因此,在我的例子中,它将是:https://domain.com/set-images/?setting=1.

此外,一旦执行了脚本,您将能够在页面上看到该类别的帖子总数、该类别中没有特色图片的帖子总数以及修改过的帖子总数。

结束

相关推荐

Featured Images for Tags?

是否可以以某种方式为标记或自定义分类创建特征图像。为了便于解释,我将给出一个可能的功能示例。假设我正在运行一个网站,发布城市中最好的餐厅。我的一些标签可能是伦敦、巴黎、纽约等等。。。我有一个页面可以抓取这些标签并按字母顺序排序。但不仅仅是文本,它还将有标签名(例如伦敦)和该城市的图像。我知道这可以手动完成,但通过将图像附加到标记或自定义分类法,可以使过程变得更简单,尤其是在处理大量标记/自定义分类法时。我认为这可能更像是一个抽象的问题,但我很好奇是否有人遇到过任何成功做到这一点的博客或网站。