web-dev-qa-db-fra.com

Dissocier les images d'un message

J'ai actuellement un type de message personnalisé dans un thème que je développe et qui sera utilisé pour les éléments du portefeuille. Jusqu'à présent, j'ai implémenté une fonctionnalité permettant aux images d'être attachées à une publication de portefeuille.

J'ai maintenant besoin de la meilleure façon de détacher des images d'un message: Mon code est actuellement:

    $images =& get_children('post_type=attachment&post_mime_type=image&post_parent=$post->ID');
            $numberOfImages = count($images);
            if($numberOfImages == 1) {

            }
            else if($numberOfImages > 1)
            {
                foreach($images as $attachment_id => $attachment)
                {
                    $imageAttributes = wp_get_attachment_image_src($attachment_id);
                    ?>
                    <div class="element">
                        <img alt="" height="100" src="<?php echo $imageAttributes[0]; ?>" width="150" />
                        <a href="#" title="Unattach this media item.">Unattach</a>
                    </div>
                    <?php
                }
            }

Cela parcourt les images attachées et les affiche dans une méta-boîte avec le bouton "Unattach" associé. Je ne sais pas à quoi/où je dois faire un lien pour détacher les images de la publication. Toute aide appréciée.

1
Darren

Cela peut être fait en utilisant un appel Ajax qui interrogera la base de données et définira le parent comme "zéro".

Tout d'abord, créez une méta-boîte, mettez en file d'attente le Javascript qui appelle la fonction unattach et enregistrez cette fonction WP_Ajax.

<?php
/*
Plugin Name: Unattach Meta Box
Version: 0.3
Author: brasofilo
Plugin URI: http://wordpress.stackexchange.com/q/54822
*/

add_action( 'add_meta_boxes', 'wpse_54822_add_custom_box' );
add_action( 'admin_head', 'wpse_54822_script_enqueuer' );
add_action( 'wp_ajax_wpse_54822_custom_query', 'wpse_54822_unattach' );
add_action( 'wp_ajax_nopriv_wpse_54822_custom_query', 'wpse_54822_unattach' );

function wpse_54822_add_custom_box() 
{
    add_meta_box(
        'wpse_54822_sectionid',
        __( 'Page Attachments' ), 
        'wpse_54822_inner_custom_box',
        'page'
    );
}

function wpse_54822_inner_custom_box() 
{
    global $post;
    $images = get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . $post->ID );
    if( count($images) > 0 )
    {
        foreach( $images as $attachment_id => $attachment )
        {
            $imageAttributes = wp_get_attachment_image_src( $attachment_id );
            ?>
            <div class="element" id="container-<?php echo $attachment_id; ?>">
                <img alt="" height="100" src="<?php echo $imageAttributes[0]; ?>" width="150" />
                <a href="javascript:void(0);" id="dettach-<?php echo $attachment_id; ?>" class="dettach" title="Unattach this media item." >Unattach</a>
            </div>
            <?php
        }
    } 
    else
    {
        echo 'No images attached.';
    }
}

function wpse_54822_script_enqueuer() 
{
    global $current_screen;
    if( 'page' != $current_screen->id )
        return;
    wp_register_script( 'scripts.js', plugin_dir_url(__FILE__).'script.js' );
    wp_enqueue_script( 'scripts.js' );
    wp_localize_script( 'scripts.js', 'wp_ajax', array( 
        'url' => admin_url( 'admin-ajax.php' ),
        'nonce' => wp_create_nonce('nonce_wpse_54822')
    )); 
}

function wpse_54822_unattach()
{
    check_ajax_referer( 'nonce_wpse_54822' );
    global $post, $wpdb;
    if( !isset( $_POST['the_attach_id'] ) )
        wp_send_json_error( array( 'error' => 'ID not set' ) );

    $the_id = intval( $_POST['the_attach_id'] );
    $do_query = $wpdb->query( $wpdb->prepare( 
        "UPDATE $wpdb->posts SET post_parent = 0 WHERE ID = '%s'", 
        $the_id 
    ));

    if( !$do_query ) {
        wp_send_json_error( array( 'error' => 'Query error.' ) ); // Refine this to show proper wpdb error
    }
    else {
        wp_send_json_success();
    }
}

Ceci est le fichier Javascript mis en file d'attente (script.js). Il effectue l'appel Ajax qui exécutera une requête MySql pour annuler l'attachement et supprime la vignette de la boîte méta.

jQuery(document).ready( function($) 
{       
    $('.dettach').each( function(i,e)
    {
        var id = $(this).attr('id').replace(/dettach-/, '');
        $(this).click( function(){
            $.post( 
                wp_ajax.url, 
                { 
                    action: 'wpse_54822_custom_query', 
                    _ajax_nonce: wp_ajax.nonce, 
                    the_attach_id: id
                }, 
                function( response ){
                    if( !response.success )
                        console.log( response.data.error );
                    else
                        remove_image( id );
                }
            );
        });
     });                 

    function remove_image( id )
    {
        $('#container-'+id).remove();
        return false;
    }
});  

Résultat:
unattach meta box

6
brasofilo