wordpress批量将媒体库里的图片发布成文章,一个图片对应一篇文章,以下代码仅供参考:
// 添加自定义批量操作到媒体库
function add_custom_media_bulk_action($actions) {
$actions['custom_action'] = __('批量创建文章', 'textdomain');
return $actions;
}
add_filter('bulk_actions-upload', 'add_custom_media_bulk_action');
// 处理自定义批量操作
function handle_media_bulk_action($redirect_to, $action, $post_ids) {
if ($action !== 'custom_action') {
return $redirect_to; // 不是我们的操作,直接返回
}
// 检查权限
if (!current_user_can('edit_posts')) {
wp_die('无权限操作');
}
// 遍历选中的图片并创建文章
foreach ($post_ids as $attachment_id) {
$image_url = wp_get_attachment_url($attachment_id);
$post_id = wp_insert_post([
'post_title' => '图片文章: ' . get_the_title($attachment_id),
'post_content' => '<img src="' . esc_url($image_url) . '" alt="' . get_the_title($attachment_id) . '">',
'post_status' => 'publish',
'post_type' => 'post',
]);
}
// 重定向到文章列表或自定义页面
return admin_url('edit.php?post_type=post');
}
add_filter('handle_bulk_actions-upload', 'handle_media_bulk_action', 10, 3);
// 添加 JavaScript 代码
function enqueue_media_bulk_action_script() {
if (get_current_screen()->id !== 'upload') {
return;
}
wp_enqueue_script('jquery');
wp_add_inline_script('jquery', "
jQuery(document).ready(function($) {
$('select[name=\"action\"]').on('change', function() {
if ($(this).val() === 'custom_action') {
$('#doaction').click(); // 提交表单
}
});
});
");
}
add_action('admin_enqueue_scripts', 'enqueue_media_bulk_action_script');


0 个评论