WordPress 特色图片 |匹配图像文件名的所有 Post Slugs [英] WordPress Featured Image | All Post Slugs Matching Image File Name

查看:30
本文介绍了WordPress 特色图片 |匹配图像文件名的所有 Post Slugs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个博客上有一堆旧帖子,我想为其分配特色图片.

I have a bunch of old posts on a blog that I would like to assign a featured image to.

我已经检索了我想用于每个帖子的所有图片.

I have retrieved all the images I would like to use for each post.

我在每个帖子的 slug 之后保存了每个图像文件名.

I saved each image file name after the slug of each post.

我想检索所有帖子,从每个帖子中获取 slug 名称,搜索上传图片文件的指定目录,当帖子 slug 与图片文件名匹配时,将该图片设置为该特定图片的特色图片发布,并遍历所有帖子.

I would like to retrieve all posts, grab the slug name from each post, search the specified directory where the image files are uploaded, when the post slug matches the image file name, set that image as the featured image for that particular post, and iterate through all posts.

我不知道该怎么做,但我提供了一些我找到的示例代码,以及一些有用的(希望如此)链接.

I am not sure how to go about doing this, but I have provided some example code I found, along with a few useful (hopefully) links.

以下代码用于检索所有帖子并更新特定帖子:

$allPosts = get_posts(array('numberposts' => -1, 'post_type' => 'post'));
foreach($allPosts as $thePost){
    $my_post = array();
    $my_post['post_type'] = $thePost->post_type;
    $my_post['ID'] = $thePost->ID;
    $my_post['post_name'] = autoSlug($thePost->post_title);
    wp_update_post($my_post);
}

注意:我有一个基于 post_title 生成 post slug 的特殊函数.(我不使用 WP 默认 slug.)

Note: I have a special function for generating post slugs based off the post_title. (I don't use the WP default slug.)

有用的链接:

  1. http://codex.wordpress.org/Template_Tags/get_posts
  2. http://codex.wordpress.org/Function_Reference/wp_update_post
  3. http://codex.wordpress.org/Post_Thumbnails
  4. http://codex.wordpress.org/Function_Reference/wp_upload_dir
  5. http://codex.wordpress.org/Function_Reference/wp_insert_attachment

推荐答案

自己写了一个脚本,同时写了一篇博文.对改进的贡献表示赞赏.请参阅此链接以获得答案 为指定目录中匹配图像文件名的所有 Post Slugs 设置 WordPress 特色图像:

Wrote a script myself, along with a blog post. Contributions for improvements are appreciated. Refer to this link for answer Set WordPress Featured Image For All Post Slugs Matching Image File Name in Specified Directory:

<?php
// Get All Posts.
$allPosts = get_posts(array('numberposts' => -1, 'post_type' => 'post'));
// Specify where the images are located.
$themePATH = get_theme_root().'/'.get_template().'/thumbs/';
// The uploads directory for your blog.
$uploads= wp_upload_dir();
// List of images including extensions.
$images = listImages($themePATH,true);
// List of images without extensions.
$imageNames = listImages($themePATH,false);

function reverseSlug($string){
    $string = str_replace("-", " ", $string);// Convert hyphen to space
    $string = ucwords($string);// Capitalize the beginning of each word
    return $string;
}

// Retrieve all images from the specified directory.
// Output array with and without file extensions.
function listImages($dirname=".",$display) {
    $ext = array("jpg", "png", "jpeg", "gif");
    $files = array();
    if($handle = opendir($dirname)){
        while(false !== ($file = readdir($handle))){
            for($i=0;$i<sizeof($ext);$i++){
                if(strstr($file, ".".$ext[$i])){
                    $files[] = $file;
                }
            }
        }
        closedir($handle);
    }
    sort($files);
    foreach($files as $theFile){
        $info = pathinfo($theFile);
        $fileName = basename($theFile,'.'.$info['extension']);
        $files1[] = $fileName;
    }
    if($display == false){
        return ($files1);
    }
    if($display == true){
        return($files);
    }
}

for($i = 0; $i < count($allPosts); $i++){
    // Check if post slugs match image slugs.
    $check[$i] = in_array($allPosts[$i]->post_name, $imageNames);
    if($check[$i] == 1){
        echo 'Yes, post title matches image name.<br />'.PHP_EOL;
        // Search through the image slugs for a direct match with the post slug.
        $search[$i] = array_search($allPosts[$i]->post_name, $imageNames);
        $filename = $images[$search[$i]];
        $newfile = $uploads['path'].'/'.$filename;
        // Copy the image from theme folder to uploads directory.
        copy($themePATH.$filename, $newfile);
        // Delete image from theme folder.
        unlink($themePATH.$filename);
        // Retrieve the file type from the file name.
        $wp_filetype = wp_check_filetype(basename($filename), null);
        // Construct the attachment array.
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'guid' => $uploads['url'].'/'.$filename,
            'post_title' => preg_replace('/\.[^.]+$/', '', reverseSlug(basename($filename))),
            'post_content' => '',
            'post_status' => 'inherit'
        );
        // This function inserts an attachment into the media library.
        $attach_id = wp_insert_attachment($attachment, $newfile, $allPosts[$i]->ID);
        // You must first include the image.php file
        // For the function wp_generate_attachment_metadata() to work.
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        // This function generates metadata for an image attachment.
        // It also creates a thumbnail and other intermediate sizes
        // of the image attachment based on the sizes defined on
        // the Settings_Media_Screen.
        $attach_data = wp_generate_attachment_metadata($attach_id, $newfile);
        if(!is_wp_error($attach_id)){
            // Update metadata for an attachment.
            wp_update_attachment_metadata($attach_id, $attach_data);
            // Updates the value of an existing meta key (custom field) for the specified post.
            update_post_meta($allPosts[$i]->ID, '_thumbnail_id', $attach_id);
        }
    }
    else{
        echo 'No matches found.<br />'.PHP_EOL;
    }
}
?>

这篇关于WordPress 特色图片 |匹配图像文件名的所有 Post Slugs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆