web-dev-qa-db-fra.com

Comment ajouter "Coller ce message sur la page de couverture"?

J'ai un site Web lié au baseball avec plusieurs auteurs. J'utilise le "Coller ce message à la page d'accueil" pour désigner un "Choix de l'éditeur" sur un article. Je voudrais ajouter un lien/bouton pour permettre à l'éditeur de le faire depuis le début. La méthode peut être soit dans l'article lui-même ou dans la barre d'administration. Je n'ai pas vraiment de préférence.

J'ai parcouru de très nombreux plug-ins "Admin Bar", mais je n'ai rien trouvé sur "Coller cet article sur la page d'accueil".

Merci

6
Travis Pflanz

Je pense que ce petit code source est votre solution. Il n’a actuellement pas de retour d’interface pour la modification de Sticky Post, mais vous pouvez améliorer cette chaîne, cette classe ou ce que vous voulez dans la fonction fb_stick_post.

La première fonction ajoute l'élément dans la barre d'administration et crée une nouvelle URL avec une valeur param. De plus, on click appelle une fonction pour lire le paramètre Url et, si c'est vrai, alors changez le statut persistant de cet identifiant de publication.

add_action( 'admin_bar_menu', 'fb_add_admin_bar_sticky', 35 );
function fb_add_admin_bar_sticky() {
    global $wp_admin_bar;

    if ( ! is_super_admin() || ! is_admin_bar_showing() )
        return;

    $current_object = get_queried_object();
    if ( empty($current_object) )
        return;

    if ( ! empty( $current_object->post_type ) && 
        ( $post_type_object = get_post_type_object( $current_object->post_type ) ) && 
        current_user_can( $post_type_object->cap->edit_post, $current_object->ID ) 
    ) {
        $wp_admin_bar->add_menu( 
            array(
                'id' => 'sticky_post', 
                'title' => __('Sticky'), 
                'href' => get_permalink() . '?stick_post=true', 
                'meta' => array(
                    'title' => __( 'Click me' ),
                    'onclick' => fb_stick_post( get_the_ID() )
                )
            )
        );
    }
}

function fb_stick_post( $post_id ) {

    if ( isset($_GET['stick_post']) && 'true' == htmlspecialchars( $_GET['stick_post'] ) )
        stick_post( $post_id );
}

Mise à jour 07/30/2012

Maintenant, un petit plugin avec une solution facile. Le plugin ajoute un élément à l'intérieur de la barre d'administration. La chaîne du bouton à vérifier est collante et offre la possibilité de coller ou de décoller la publication actuelle.

Example in Twenty Eleven Theme for an post, there was with an sticky flag

Je modifie le crochet pour ajouter l’élément de barre d’administration à ´template_redirect` afin d’utiliser une redirection après la mise à jour de l’indicateur de bâton sur le post.

<?php
/**
 * Plugin Name: Stick/Unstick post via Admin bar
 * 
 */

if ( ! function_exists( 'fb_add_admin_bar_sticky' ) ) {

    add_action( 'template_redirect', 'fb_add_admin_bar_sticky' );
    function fb_add_admin_bar_sticky() {
        global $wp_admin_bar;

        if ( ! is_super_admin() || ! is_admin_bar_showing() )
            return;

        $current_object = get_queried_object();
        if ( empty($current_object) )
            return;

        if ( ! empty( $current_object->post_type ) && 
            ( $post_type_object = get_post_type_object( $current_object->post_type ) ) && 
            current_user_can( $post_type_object->cap->edit_post, $current_object->ID ) 
        ) {

            // check, if an sticky post
            if ( is_sticky( get_the_ID() ) ) {
                $title = __('Unsticky');
                $link = '?unstick_post=true';
                $attr_title = __( 'Make this post unsticky' );
            } else {
                $title = __('Sticky');
                $link = '?stick_post=true';
                $attr_title = __( 'Make this post sticky' );
            }

            $wp_admin_bar->add_menu(
                array(
                    'id' => 'sticky_post', 
                    'title' => $title, 
                    'href' => get_permalink() . $link, 
                    'meta' => array(
                        'title' => $attr_title,
                        'onclick' => fb_stick_post( get_the_ID() )
                    )
                )
            );
        }
    }

    function fb_stick_post( $post_id ) {

        if ( isset($_GET['stick_post']) && 'true' == htmlspecialchars( $_GET['stick_post'] ) ) {
            stick_post( $post_id );
            wp_redirect( get_permalink( $post_id ) );
            exit();
        }

        if ( isset($_GET['unstick_post']) && 'true' == htmlspecialchars( $_GET['unstick_post'] ) ) {
            unstick_post( $post_id );
            wp_redirect( get_permalink( $post_id ) );
            exit();
        }
    }

}

ou téléchargez ce plugin Gist 3214922

4
bueltge

Quelques fonctions sont utiles ici:

Avec ces trois éléments en tête, il suffit de les coller avec de la colle pour barre de menu.

Tout d’abord, emballons tout dans une classe pour le plaisir et le profit. Cette classe aura des constantes que nous utiliserons plus tard: un nonce, une action pour décoller le post et une action pour coller le post.

class WPSE_58818_Stick_Post
{
    /**
     * Ajax nonce.
     *
     * @since   1.0
     */
    const NONCE = 'wpse58818_nonce_';

    /**
     * Unstick ajax action
     *
     * @since   1.0
     */
    const UNSTICK = 'wpse58818_unstick';

    /**
     * Stick Ajax action
     *
     * @since   1.0
     */
    const STICK = 'wpse58818_stick';
} // end class

Ensuite, ajoutons une fonction init pour ajouter nos actions. La première action consiste à accrocher template_redirect.

<?php
class WPSE_58818_Stick_Post
{
    // snip snip

    /**
     * Adds actions and such.
     *
     * @since   1.0
     * @access  public
     * @uses    add_action
     */
    public static function init()
    {
        add_action(
            'template_redirect',
            array(__CLASS__, 'template_r')
        );
    }
}

NOTE: à partir de maintenant, je vais omettre le bit class. Vous pouvez voir la chose entière ici .

Dans la fonction reliée à template_redirect, nous vérifierons si nous sommes sur une seule page de publication et si l'utilisateur peut ou non la modifier. S'ils le peuvent, nous accrocherons admin_bar_menu et wp_footer.

/**
 * Hooked into `template_redirect`.  Adds the admin bar stick/unstick
 * button if we're on a single post page and the current user can edit
 * the post
 * 
 * @since   1.0
 * @access  public
 * @uses    add_action
 */
public static function template_r()
{
    if(
        !is_single() ||
        !current_user_can('edit_post', get_queried_object_id())
    ) return; // not a single post or the user can't edit it

    // Hook into admin_bar_menu to add stuff
    add_action(
        'admin_bar_menu',
        array(__CLASS__, 'menu'),
        100
    );

    // Hook into the footer and spit out some JavaScript
    add_action(
        'wp_footer',
        array(__CLASS__, 'footer')
    );
}

Dans la fonction menu, reliée à admin_bar_menu, nous pouvons ajouter notre nouvel élément:

/**
 * Hooked into `admin_bar_menu`.  Adds our stick/unstick node.
 *
 * @since   1.0
 * @access  public
 */
public static function menu($mb)
{
    // get the current post ID
    $post_id = get_queried_object_id();

    $mb->add_node(array(
        'id'    => 'wpse58818-sticker',
        'meta'  => array(
            'class' => 'wpse58818-sticker',
            'title' => is_sticky($post_id) ? 'unstick' : 'stick'
        ),
        'title' => is_sticky($post_id) ? __('Unstick') : __('Stick'),
        'href'  => self::get_url($post_id)
    ));
}

Nous avons ici notre première "fonction utilitaire" qui crée une URL pour le nœud de la barre de menus de l'administrateur. C'est juste un wrapper autour de add_query_arg to nonce, et construisons une url que nous utiliserons avec AJAX plus tard:

/**
 * Get an Ajax URL to use for a given post
 *
 * @since   1.0
 * @access  protected
 */
protected static function get_url($post_id)
{
    return add_query_arg(array(
        'post_id' => absint($post_id),
        'action'  => is_sticky($post_id) ? self::UNSTICK : self::STICK,
        'nonce'   => wp_create_nonce(self::NONCE . $post_id)
    ), admin_url('admin-ajax.php'));
}

La fonction footer crache du code JavaScript pour passer les appels AJAX. Aperçu de base: lorsque quelqu'un clique sur notre nouveau lien, faites une demande GET à l'URL donnée. En cas de succès, changez le href, le texte et le titre du lien (dé) coller.

/**
 * Hooked into `wp_footer`.  Spits out a bit of JS to stick/unstick a post
 *
 * @since   1.0
 * @access  public
 */
public static function footer()
{
    ?>
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        $('.wpse58818-sticker a').on('click', function(e) {
            e.preventDefault();
            var action = $(this).attr('title');
            var that = this;
            $.get(
                $(this).attr('href'),
                {},
                function(data) {
                    if('0' == data)
                    {
                        console.log(data);
                        alert('<?php echo esc_js(__('An error occurred')); ?>');
                        return;
                    }

                    $(that).attr('href', data);
                    if('stick' == action) {
                        $(that).html('<?php echo esc_js(__('Unstick')); ?>');
                        $(that).attr('title', 'unstick');
                    } else {
                        $(that).html('<?php echo esc_js(__('Stick')); ?>');
                        $(that).attr('title', 'stick');
                    }
                }
            );
        });
    });
    </script>
    <?php
}

Et maintenant, nous arrivons aux callbacks AJAX. Ajax dans les plugins/themes mérite d'être lu.

Nous allons un peu modifier notre fonction init pour ajouter deux actions supplémentaires:

/**
 * Adds actions and such.
 *
 * @since   1.0
 * @access  public
 * @uses    add_action
 */
public static function init()
{
    add_action(
        'template_redirect',
        array(__CLASS__, 'template_r')
    );

    // Ajax actions
    add_action(
        'wp_ajax_' . self::STICK,
        array(__CLASS__, 'stick')
    );

    add_action(
        'wp_ajax_' . self::UNSTICK,
        array(__CLASS__, 'unstick')
    );
}

Et nos AJAX callbacks. Celles-ci pourraient très facilement être la même fonction. Je les ai séparés ici parce qu'il semblait plus facile d'étendre/changer à l'avenir. Ils vérifient tous les deux si la demande AJAX est valide, collez (dé) collez le post en conséquence et annulez la nouvelle URL pour un (dés) collage futur.

/**
 * Ajax callback for the stick function
 *
 * @since   1.0
 * @access  public
 */
public static function stick()
{
    $post_id = self::can_ajax();

    stick_post($post_id);

    echo self::get_url($post_id);
    die();
}

/**
 * Ajax callback for the unstick function
 *
 * @since   1.0
 * @access  public
 * @uses    unstick_post
 */
public static function unstick()
{
    $post_id = self::can_ajax();

    // nonces checked, everything is good to go. Unstick!
    unstick_post($post_id);

    echo self::get_url($post_id);
    die();
}

Notre deuxième "fonction utilitaire" apparaît ici. can_ajax vérifie nos permissions d'accès et utilisateurs et renvoie l'identifiant de publication à (dé) coller. Si une des vérifications échoue, elle se ferme (via die('1')).

/**
 * Check to see if the current user can ajax.  Returns the post ID to 
 * stick/unstick if successful. Kills the program otherwise
 *
 * @since   1.0
 * @access  protected
 */
protected static function can_ajax()
{
    $post_id = isset($_REQUEST['post_id']) ? $_REQUEST['post_id'] : '';

    if(
        !$post_id ||
        !check_ajax_referer(self::NONCE . $post_id, 'nonce', false)
    ) die('0');

    if(!current_user_can('edit_post', $post_id))
        die('0');

    return $post_id;
}

Voici cet ensemble désordre en tant que plugin .

7
chrisguitarguy

Voici une solution beaucoup plus simple qui fera le travail en utilisant le crochet de filtre the_content

add_filter('the_content','simplest_sticky_solution');
function simplest_sticky_solution($content){
    global $post;
    //early exit if not needed
    if (!is_single() || !current_user_can('edit_post',$post->ID)) 
        return $content;

    //check if form is submitted and act as needed
    if (isset($_POST['sticky_action']) && isset($_POST['sticky_id']) && isset($_POST['sticky_nonce']) && wp_verify_nonce($_POST['sticky_nonce'], 'StickIt')){
        if (is_sticky($post->ID)){
            stick_post($post->ID);
        }else{
            unstick_post($post->ID);
        }
    }

    //create the form
    $label = (is_sticky())? "Unstick": "Stick";
    $form = '
    <form action="" method="POST">
        <input type="hidden" name="sticky_id" value="'.$post->id.'">
        <input type="hidden" name="sticky_action" value="stickit">
        <input type="hidden" name="sticky_nonce" value="'.wp_create_nonce('StickIt').'">
        <input type="button" name="submit" value="'.$label.'">
    </form>';
    return $form.'<br/>'.$content;
}
3
Bainternet