wordpress 自动获取文章第一张图片做为特色图片




wordpress 自动获取文章第一张图片做为特色图片

如标题所示 这期带来的是特色图片自动生成代码
该代码能获取文章的第一张图片 然后将此图片存放到本地空间并设置为特色图片
相比其他只能获取本站图片的生成代码 这代码确实是非常强大

 <?php
add_action('publish_post', 'ipc_publish_post');
/**
 * Function to save first image in post as post thumbmail.
 */
function ipc_publish_post($post_id)
{
    global $wpdb;
    // First check whether Post Thumbnail is already set for this post.
    if (get_post_meta($post_id, '_thumbnail_id', true) || get_post_meta($post_id, 'skip_post_thumb', true)) {
        return;
    }
    $post = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE id = {$post_id}");
    // Initialize variable used to store list of matched images as per provided regular expression
    $matches = array();
    // Get all images from post's body
    preg_match_all('/<\\s*img [^\\>]*src\\s*=\\s*[\\""\']?([^\\""\'>]*)/i', $post[0]->post_content, $matches);
    if (count($matches)) {
        foreach ($matches[0] as $key => $image) {
            /**
             * If the image is from wordpress's own media gallery, then it appends the thumbmail id to a css class.
             * Look for this id in the IMG tag.
             */
            preg_match('/wp-image-([\\d]*)/i', $image, $thumb_id);
            $thumb_id = $thumb_id[1];
            // If thumb id is not found, try to look for the image in DB. Thanks to "Erwin Vrolijk" for providing this code.
            if (!$thumb_id) {
                $image = substr($image, strpos($image, '"') + 1);
                $result = $wpdb->get_results(("SELECT ID FROM {$wpdb->posts} WHERE guid = '" . $image) . '\'');
                $thumb_id = $result[0]->ID;
            }
            // Ok. Still no id found. Some other way used to insert the image in post. Now we must fetch the image from URL and do the needful.
            if (!$thumb_id) {
                $thumb_id = ipc_generate_post_thumb($matches, $key, $post[0]->post_content, $post_id);
            }
            // If we succeed in generating thumg, let's update post meta
            if ($thumb_id) {
                update_post_meta($post_id, '_thumbnail_id', $thumb_id);
                break;
            }
        }
    }
}
// end ipc_publish_post()
/**
 * Function to fetch the image from URL and generate the required thumbnails
 */
function ipc_generate_post_thumb($matches, $key, $post_content, $post_id)
{
    // Make sure to assign correct title to the image. Extract it from img tag
    $imageTitle = '';
    preg_match_all('/<\\s*img [^\\>]*title\\s*=\\s*[\\""\']?([^\\""\'>]*)/i', $post_content, $matchesTitle);
    if (count($matchesTitle) && isset($matchesTitle[1])) {
        $imageTitle = $matchesTitle[1][$key];
    }
    // Get the URL now for further processing
    $imageUrl = $matches[1][$key];
    // Get the file name
    $filename = substr($imageUrl, strrpos($imageUrl, '/') + 1);
    if (!(($uploads = gogo_upload_dir(current_time('mysql'))) && false === $uploads['error'])) {
        return null;
    }
    // Generate unique file name
    $filename = gogo_unique_filename($uploads['path'], $filename);
    // Move the file to the uploads dir
    $new_file = $uploads['path'] . "/{$filename}";
    if (!ini_get('allow_url_fopen')) {
        $file_data = curl_get_file_contents($imageUrl);
    } else {
        $file_data = @file_get_contents($imageUrl);
    }
    if (!$file_data) {
        return null;
    }
    file_put_contents($new_file, $file_data);
    // Set correct file permissions
    $stat = stat(dirname($new_file));
    $perms = $stat['mode'] & 438;
    @chmod($new_file, $perms);
    // Get the file type. Must to use it as a post thumbnail.
    $gogo_filetype = gogo_check_filetype($filename, $mimes);
    extract($gogo_filetype);
    // No file type! No point to proceed further
    if ((!$type || !$ext) && !current_user_can('unfiltered_upload')) {
        return null;
    }
    // Compute the URL
    $url = $uploads['url'] . "/{$filename}";
    // Construct the attachment array
    $attachment = array('post_mime_type' => $type, 'guid' => $url, 'post_parent' => null, 'post_title' => $imageTitle, 'post_content' => '');
    $thumb_id = gogo_insert_attachment($attachment, $file, $post_id);
    if (!is_gogo_error($thumb_id)) {
        require_once ABSPATH . '/wp-admin/includes/image.php';
        // Added fix by misthero as suggested
        gogo_update_attachment_metadata($thumb_id, gogo_generate_attachment_metadata($thumb_id, $new_file));
        update_attached_file($thumb_id, $new_file);
        return $thumb_id;
    }
    return null;
}

加载到主题functions.php中
以后只要有写带图片的文章 他会自动帮你生成特色图片
wordpress 自动获取文章第一张图片做为特色图片
如图所示的 就是该代码自动生成的

ps:该代码出自插件auto post thumbnail
这里只将生成代码扣取出来
插件详细请浏览:wordpress–自动生成特色图片

going

我还没有学会写个人说明!

暂无评论

相关推荐

数据库优化小窍门及全站优化

刚用wordpress的朋友细心一点可能会发现,每当当发表或编辑一篇文章,保存有十几个草稿版本的时候,会增加很多垃圾数据,无形之中增大数据库压力,wordpress本身就有反映慢等缺点,对于用户体验来说有一定影响。 ...

影响网站优化收录的因素大盘点

网站优化的收录问题,一直是SEOer比较关心也时常为此头疼的问题。百度关键词排名,很重要的一个指标就是网站收录量。网站收录量高与内容质量高,更新规律,域名时间久等因素有关,但是还有一些其他因素在影响着 ...

解决登陆wordpress后台无法登录问题

解决登陆wordpress后台无法登录问题 博客安装好了之后,点击登录,却页面显示空白。这是为什么呢? 试着谷歌了一下,找到了下面三个原因: 插件不兼容问题 wordpress博客出现莫名其妙的问题,大部分都是因为不兼 ...

关注公众号,进入小程序