問題描述

我有一個與多個作者的棒球相關的網站。我使用 「堅持這個帖子到首頁」 來表示一篇文章的 「編輯選擇」 。我想新增一個連結/按鈕,以允許編輯器從前端執行此操作。該方法可以在文章本身或管理欄中。我真的不喜歡

我看過許多很多不同的”Admin Bar” 外掛,但是還沒有找到任何有關 「貼上這個帖子到首頁」 的內容。

謝謝

最佳解決方案

我認為這個小的原始碼是你的解決方案。它目前沒有前貼補丁的更改,但您可以增強這個字串,類或任何你想要的功能 fb_stick_post

第一個功能在管理欄中新增專案,並建立一個具有 param 值的新 Url 。另外,on click 呼叫一個函式來讀取 Url 引數,如果是這樣,那麼對這個帖子 id 的粘性狀態進行更改。

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 );
}

更新 07/30/2012

現在一個小外掛,方便解決。該外掛在管理欄中新增一個專案。按鈕檢查的字串是粘性的,並提供貼上或解除當前帖子的可能性。

我更改掛鉤,將管理員條目新增到’template_redirect`,以便在更新帖子標記後使用重定向。

<?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();
        }
    }

}

或者下載這個外掛 Gist 3214922

次佳解決方案

有幾個功能在這裡派上用場:

  • unstick_post – 打破一個職位

  • stick_post – 貼一個帖子

  • is_sticky – 找出一個帖子是否粘稠

考慮到這三個因素,我們需要做的就是將它們貼上在一起,並配置一些管理選單欄膠水。

首先,讓我們把一切都包裝在一個課堂裡,以獲取樂趣和利潤。這個類將有一些常量,我們稍後將使用:一個隨機數,一個用於取消列印帖子的動作和一個貼上該帖子的動作。

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

然後我們新增一個 init 函式來新增我們的操作。第一個動作是我們掛鉤到 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')
        );
    }
}

注意:從這裡開始,我將省略 class 位。您可以檢視 here 的全部內容。

在掛接到 template_redirect 的函式中,我們將檢查我們是否在一個單獨的頁面上,以及使用者是否可以編輯它。如果可以的話,我們將掛接到 admin_bar_menuwp_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')
    );
}

menu 功能中,加入了 admin_bar_menu,我們可以新增我們的新專案:

/**
 * 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)
    ));
}

在這裡,我們獲得了第一個為管理選單欄節點構建一個 URL 的”utility function” 。它只是 add_query_arg 的一個封裝,並且構建一個我們將在 AJAX 中使用的 URL:

/**
 * 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'));
}

footer 功能只是吐出一些 JavaScript 來進行 AJAX 呼叫。基本概述:當有人點選我們的新連結時,向給定的 URL 發出 GET 請求。如果成功,請更改 (un)stick 連結的 href,文字和標題。

/**
 * 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
}

現在我們來到 AJAX 回撥。 Ajax in plugins/themes 值得一讀。

我們將修改 init 功能,再新增兩個動作:

/**
 * 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')
    );
}

和我們的 AJAX 回撥。這些可以很容易地是相同的功能。我把它們分開了,因為它在將來更容易擴充套件/改變。這兩個都檢查 AJAX 請求是否有效,(un) 貼上相應的帖子,並回撥出新的 URL 以便將來 (un) 貼上。

/**
 * 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();
}

我們的第二個”utility function” 在這裡出現。 can_ajax 驗證我們的使用者許可權,並將帖子 ID 返回 (un) 。如果任何檢查失敗,它將退出 (透過 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;
}

這是整個 mess as a plugin

第三種解決方案

這是一個更簡單的解決方案,將使用 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;
}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。