У меня была та же проблема - у меня были настраиваемые поля в нескольких сообщениях, которые содержали URL-адреса, которые я хотел использовать для избранных изображений. Я знал, что некоторые изображения уже были в моей медиабиблиотеке, поэтому я сделал следующие функции, чтобы добавить действие массового редактирования в окно редактора, которое циклически перебирает сообщения и загружает изображения там, где изображения еще не было в библиотеке, или получили идентификатор изображения, уже находящегося в библиотеке, а затем установите его в качестве нового избранного изображения для публикации.
Это грубый код, но он работает нормально - пожалуйста, сделайте резервную копию своего сайта, прежде чем делать это.
function does_file_exists($filename) {
global $wpdb;
$data = $wpdb->get_results( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_value LIKE '%/$filename'" );
foreach ($data as $ID){
$ID = $ID->post_id;
if (get_post_type($ID) == "attachment"){
return $ID;
}
}
return null;
}
function upload_image_from_URL($image_url, $post_id){
// Add Featured Image to Post
$image_name = pathinfo($image_url)['basename'];
$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 );
return $attach_id;
}
function set_featured_image($post_id){
if (wp_is_post_revision($post_id)) return;
if (has_post_thumbnail($post_id)) return;
$image_url = get_field('FIELD_NAME', $post_id);
if ($image_url){
$attachment_ID = does_file_exists(pathinfo($image_url)['basename']);
$attachment_ID = ($attachment_ID ? $attachment_ID : upload_image_from_URL($image_url, $post_id));
if ($attachment_ID){
$message = "Setting attachment ". $attachment_ID ." to post ". $post_id;
error_log($message);
set_post_thumbnail($post_id, $attachment_ID);
}
}
}
add_filter( 'bulk_actions-edit-post', 'register_bulk_update_featured_image' );
function register_bulk_update_featured_image($bulk_actions) {
$bulk_actions['update_featured_image'] = "Get featured image from field";
return $bulk_actions;
}
add_filter( 'handle_bulk_actions-edit-post', 'bulk_update_featured_image', 10, 3 );
function bulk_update_featured_image( $redirect_to, $doaction, $post_ids ) {
if ( $doaction !== 'update_featured_image' ) {
return $redirect_to;
}
foreach ( $post_ids as $post_id ) {
// Perform action for each post.
set_featured_image($post_id);
}
$redirect_to = add_query_arg( 'bulk_updated_featured_images', count( $post_ids ), $redirect_to );
return $redirect_to;
}
add_action( 'admin_notices', 'my_bulk_action_admin_notice' );
function my_bulk_action_admin_notice() {
if ( ! empty( $_REQUEST['bulk_updated_featured_images'] ) ) {
$id_count = intval( $_REQUEST['bulk_updated_featured_images'] );
printf('<div id="message" class="updated fade">Updated %s featured images.</div>',
$id_count);
}
}
person
Emil
schedule
13.10.2018