You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress Media Uploader:如何在特色图片弹窗添加自定义按钮

Hey there! I’ve tackled this exact scenario before, so let me walk you through how to add a custom button right alongside the "Set featured image" button in the WordPress Featured Image popup. Here's a step-by-step implementation that works reliably:

Step 1: Enqueue Your Custom Script (PHP)

First, we need to load our custom JavaScript on post edit screens only. Add this code to your theme's functions.php file (or a custom plugin):

function enqueue_custom_featured_image_button_script() {
    // Only load on post edit/admin screens
    if ( ! is_admin() || ! get_current_screen()->is_post_type() ) {
        return;
    }

    // Enqueue the script, depending on jQuery and WordPress media editor scripts
    wp_enqueue_script(
        'custom-featured-image-btn',
        get_stylesheet_directory_uri() . '/js/custom-featured-btn.js', // Adjust path to your JS file
        array( 'jquery', 'media-editor' ),
        wp_get_theme()->get('Version'),
        true // Load in footer
    );
}
add_action( 'admin_enqueue_scripts', 'enqueue_custom_featured_image_button_script' );

Step 2: Write the JavaScript to Add the Button

Create a new JS file at the path you specified above (e.g., wp-content/themes/your-theme/js/custom-featured-btn.js) and add this code:

jQuery(document).ready(function($) {
    // Listen for when the Featured Image popup is opened
    $(document).on('click', '.set-post-thumbnail', function() {
        // Wait a short moment for the popup to fully render
        setTimeout(function() {
            // Target the container holding the "Set featured image" button
            const setButton = $('.media-toolbar-primary .media-button-select');
            
            // Only add the button if it doesn't already exist
            if (setButton.length && !$('.media-button-custom').length) {
                // Create our custom button
                const customBtn = $(`
                    <button type="button" class="button media-button-custom">
                        *My Custom Action*
                    </button>
                `);
                
                // Insert it right after the "Set featured image" button
                setButton.after(customBtn);
                
                // Add click functionality to the custom button
                customBtn.on('click', function(e) {
                    e.preventDefault();
                    
                    // Get the currently selected attachment(s) from the popup
                    const selectedMedia = wp.media.frame.state().get('selection');
                    
                    // Loop through selected items (handle single/multiple selections)
                    selectedMedia.each(function(attachment) {
                        const attachmentData = attachment.toJSON();
                        // Do your custom logic here!
                        console.log('Selected attachment ID:', attachmentData.id);
                        console.log('Attachment URL:', attachmentData.url);
                        // Example: Show an alert with the attachment ID
                        alert(`You picked attachment #${attachmentData.id}`);
                    });
                    
                    // Optional: Close the popup after your action runs
                    // wp.media.frame.close();
                });
            }
        }, 400);
    });
});

Alternative: Use Inline Script (No Separate JS File)

If you don't want to create a separate JS file, you can inject the script directly via PHP:

function add_inline_custom_featured_button_script() {
    if ( ! is_admin() || ! get_current_screen()->is_post_type() ) {
        return;
    }

    // Add inline script that depends on the media-editor script
    wp_add_inline_script( 'media-editor', '
        jQuery(document).ready(function($) {
            $(document).on("click", ".set-post-thumbnail", function() {
                setTimeout(function() {
                    const setButton = $(".media-toolbar-primary .media-button-select");
                    if (setButton.length && !$(".media-button-custom").length) {
                        const customBtn = $(\'<button type="button" class="button media-button-custom">*My Custom Action*</button>\');
                        setButton.after(customBtn);
                        customBtn.on("click", function(e) {
                            e.preventDefault();
                            const selectedMedia = wp.media.frame.state().get("selection");
                            selectedMedia.each(function(attachment) {
                                const data = attachment.toJSON();
                                // Your custom code here
                                console.log("Custom action triggered for:", data.title);
                            });
                        });
                    }
                }, 400);
            });
        });
    ' );
}
add_action( 'admin_enqueue_scripts', 'add_inline_custom_featured_button_script' );

Key Notes & Customization Tips

  • Avoid Duplicate Buttons: The check !$('.media-button-custom').length ensures we don't add multiple instances of the button if the popup is opened/closed multiple times.
  • Styling: Use the class media-button-custom to style your button (match WordPress's admin UI with CSS if needed).
  • Popup Detection: For a more precise approach (instead of setTimeout), you can listen to the open event of the media modal:
    wp.media.view.Modal.prototype.on('open', function() {
        const frame = this.content.get();
        // Only target the Featured Image popup
        if (frame.options.id === 'featured-image') {
            // Add your button creation logic here
        }
    });
    
  • Custom Logic: Replace the console logs/alerts with your own functionality—like sending the attachment data to an API, updating post meta, etc.

内容的提问来源于stack exchange,提问作者jaguwalapratik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:21:41