wordpress收费下载资源主题
wordpress付费下载资源插件

wordpress如何将媒体库里的图片直接发布成文章

如果需要快速将媒体库里的图片发布成文章,可以将以下代码添加到主题的 functions.php 文件或自定义插件中:

// 添加自定义按钮到媒体库列表
function add_custom_media_button($actions, $post) {
if (get_post_type($post) === 'attachment') {
$actions['create_post'] = '<a href="#" data-attachment-id="' . $post->ID . '" class="create-post-from-image">创建文章</a>';
}
return $actions;
}
add_filter('media_row_actions', 'add_custom_media_button', 10, 2);

// 处理 AJAX 请求创建文章
function handle_create_post_from_image() {
if (!isset($_POST['attachment_id'])) {
wp_send_json_error('缺少图片ID');
}

$attachment_id = intval($_POST['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="' . esc_attr(get_post_meta($attachment_id, '_wp_attachment_image_alt', true)) . '" />',
'post_status' => 'publish',
'post_type' => 'post',
]);

if ($post_id) {
wp_send_json_success(['redirect' => get_permalink($post_id)]);
} else {
wp_send_json_error('文章创建失败');
}
}
add_action('wp_ajax_create_post_from_image', 'handle_create_post_from_image');

// 添加前端脚本
function enqueue_media_scripts() {
wp_enqueue_script('jquery');
wp_add_inline_script('jquery', "
jQuery(document).ready(function($) {
$(document).on('click', '.create-post-from-image', function(e) {
e.preventDefault();
var attachmentId = $(this).data('attachment-id');

$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'create_post_from_image',
attachment_id: attachmentId,
_ajax_nonce: '" . wp_create_nonce('create-post-from-image') . "'
},
success: function(response) {
if (response.success) {
window.location.href = response.data.redirect;
} else {
alert('错误: ' + response.data);
}
}
});
});
});
");
}
add_action('admin_enqueue_scripts', 'enqueue_media_scripts');

代码实现了媒体库里每个图片都增加了一个 发布文章 按钮,点一下就可以发布一篇文章。

0 个评论

定制开发
本站承接WordPress等系统建站仿站、二次开发、主题插件定制等开发服务
在线咨询
  • 请先加Q,临时会话收不到
    QQ:1-247-246-247

  • QQ一群:104228692(满)
  • QQ二群:64786792
在线咨询
本站承接WordPress建站仿站、二次开发、主题插件定制等PHP开发服务!

了解详情