17713433920 info@mac163.com
如何从WordPress中的URL添加特色图片
如何从WordPress中的URL添加特色图片

有时,您需要从另一台服务器(而不是您的WordPress安装正在运行的服务器)动态地将特色图片添加到帖子或自定义帖子类型中。您面临一个共同的问题:该怎么做?

当然,在这种情况下,您需要从第二台服务器获取特色图像,将其下载到自己的服务器的上载文件夹中,然后将其分配给正确的帖子。第一步,我们将动态创建一个新帖子,然后处理特色图片。

第1步:动态创建帖子

要动态创建帖子,您需要使用  wp_insert_post()函数。您可以将下面的代码放在“ IF”语句中,否则每次加载页面时都会创建一个新帖子。没那么方便。

// Register Post Data
$post = array();
$post['post_status']   = 'publish';
$post['post_type']     = 'post'; // can be a CPT too
$post['post_title']    = 'My New Post';
$post['post_content']  = 'My new post content';
$post['post_author']   = 1;

// Create Post
$post_id = wp_insert_post( $post );

运行此代码将仅创建一个新帖子。现在是时候添加特色图片了。

第2步:添加特色图片

要从URL添加特色图片,我们必须使用一些WordPress功能:

现在是代码。我评论了每个操作,以便您可以确切地看到运行此脚本时发生的情况。

// Add Featured Image to Post
$image_url        = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here
$image_name       = 'wp-header-logo.png';
$upload_dir       = wp_upload_dir(); // Set upload folder
$image_data       = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
$filename         = basename( $unique_file_name ); // Create image file name

// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
    $file = $upload_dir['path'] . '/' . $filename;
} else {
    $file = $upload_dir['basedir'] . '/' . $filename;
}

// Create the image  file on the server
file_put_contents( $file, $image_data );

// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );

// Set attachment data
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title'     => sanitize_file_name( $filename ),
    'post_content'   => '',
    'post_status'    => 'inherit'
);

// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );

// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');

// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );

// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );

// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );

这段代码有趣的是,您可以将其放在循环中。例如,从CSV文件或XML文件导入帖子。这确实很强大并且非常有用,但是请不要忘记一件事:切勿在没有放置条件标记的情况下在当前WordPress主题的functions.php函数文件中使用此脚本,否则您将在几分钟之内收到数百篇新文章!


微信二维码

微信扫描二维码联系我们!
我们在微信上24小时期待你的声音
提供外贸路由器设备产品,轻松翻墙,解答:WP主题推荐,WP网站建设,Google SEO,百度SEO,专业服务器环境搭建等!


需要提供WordPress主题/插件的汉化服务可以随时联系我们!另外成品WordPress网站以及半成品WordPress网站建设,海外Google SEO优化托管服务,百度SEO优化托管服务,Centos/Debian服务器WP专用环境搭建,WP缓存服务器搭建,我们都是你的首选,拥有多年WP开源程序服务经验,我们一直在坚持客户体验,没有最好,只有更好!
回到顶部