首页 > 解决方案 > 单击按钮时执行简码

问题描述

我在帖子创建器中使用元框来存储本文所述的额外内容

现在,我想通过单击类似于此帖子的按钮来执行短代码 [extra] ,但我无法使其正常工作。

到目前为止,这是我的代码:

jQuery

    jQuery(document).ready(function($) {
        $('#extra').on('click',function() {
            $.ajax({
                type: "POST", 
                url: my_ajaxurl, 
                data: {
                    action : 'process_shortcode_on_click_action'
                },
                success:function(data) {
                    console.log("Success");
                },
                error: function(errorThrown){
                    console.log("Error");
                }
            });
        })
    })

函数.php

    add_action( 'wp_enqueue_scripts', 'add_my_script' );
    function add_my_script() {
        wp_enqueue_script(
            'extra-script', // name your script so that you can attach other scripts and de-register, etc.
            get_template_directory_uri() . '/js/script.js', // this is the location of your script file
            array('jquery') // this array lists the scripts upon which your script depends
        );
        wp_localize_script( 'extra-script', 'my_ajaxurl', admin_url( 'admin-ajax.php' ) );
    }
    
    add_shortcode( 'extra',  't5_extra_content' );
    add_action( 'add_meta_boxes_post', 't5_register_extra_metabox' );
    add_action( 'save_post', 't5_save_shortcode_box', 10, 2);
    add_action( 'wp_ajax_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
    add_action( 'wp_ajax_nopriv_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
    
    function process_shortcode_on_click_ajax() {
        echo do_shortcode('[extra]');
        die;
    }
    
    function t5_extra_content( $attributes, $content = '' )
    {
        $args = shortcode_atts( array ( 'cap' => 'edit_posts' ), $attributes );
            if ( current_user_can( $args['cap'] ) )
            return wpautop(
            get_post_meta( get_the_ID(), '_t5_extra_box', TRUE )
                . $content
            );
    }
    
    function t5_register_extra_metabox()
    {
        add_meta_box(
            't5_extra',
            'My Point of View',
            't5_extra_metabox_callback',
            NULL, // screen
            'normal',
            'default'
        );
    }
    function t5_extra_metabox_callback( $post )
    {
        $nonce = wp_create_nonce( __FILE__ );
        echo "<input type='hidden' name='t5_extra_box_nonce' value='$nonce' />";
        $content = get_post_meta($post->ID, '_t5_extra_box', TRUE );
        wp_editor(
            $content,
            '_t5_extra_box',
            array (
                'textarea_rows' => 10,
                'media_buttons' => FALSE,
                'teeny'         => TRUE,
                'tinymce'       => TRUE
            )
        );
    }
    function t5_save_shortcode_box( $post_id )
    {
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE
            or ! isset ( $_POST['post_type'] )
            or 'post' !== $_POST['post_type']
            or ! current_user_can( 'edit_post', $post_id )
            or ! wp_verify_nonce( $_POST[ 't5_extra_box_nonce' ], __FILE__ )
        )
        {
            return;
        }
    
        if ( isset ( $_POST['_t5_extra_box'] ) )
            update_post_meta( $post_id, '_t5_extra_box', $_POST['_t5_extra_box'] );
        else
            delete_post_meta( $post_id, '_t5_extra_box' );
    }

我在控制台中看到“成功”,所以我知道 jQuery 被正确调用。但是,我不知道如何让 do_shortcode('[extra]') 触发。任何帮助是极大的赞赏。

标签: phpjquerywordpress

解决方案


您的 ajax 调用没有$post来自 ajax 请求来自的页面的全局内容,因此get_the_ID()应该是假的,get_post_meta( get_the_ID(), '_t5_extra_box', TRUE )也应该是假的。此外,您正在调用do_shortcode('[extra]')(无内容),因此$content在您的回调中将是一个空字符串。所以return wpautop(get_post_meta( get_the_ID(), '_t5_extra_box', TRUE).$content);变成return wpautop('');了它只是一个空字符串。根据您的代码,我希望您的data响应始终是空字符串。

为了解决这个问题,我将添加一个额外的 ajax 发布数据项以及告诉回调$post_id应该是什么的操作。这是最原始的方式。您可能想要添加随机数或其他一些安全措施(但这可能与您的原始问题无关)。

更新

我没有对此进行测试,您可能希望以不同的方式进行操作,但这是一种选择。最终,您只需要一种$post_id从原始请求中获取并将其传递给 ajax 调用的方法。由于您已经通过 ajax url 传递了wp_localize_script,我将在那里添加另一个 JavaScript 变量。

jQuery

jQuery(document).ready(function ($) {
    $('#extra').on('click', function () {
        $.ajax({
            type: "POST",
            url: my_ajaxurl,
            data: {
                action: 'process_shortcode_on_click_action',
                post_id: my_postid,
            },
            success: function (data) {
                console.log("Success");
            },
            error: function (errorThrown) {
                console.log("Error");
            }
        });
    })
})

函数.php

add_action('wp_enqueue_scripts', 'add_my_script');
function add_my_script () {
    wp_enqueue_script(
        'extra-script', // name your script so that you can attach other scripts and de-register, etc.
        get_template_directory_uri() . '/js/script.js', // this is the location of your script file
        array('jquery') // this array lists the scripts upon which your script depends
    );
    wp_localize_script('extra-script', 'my_ajaxurl', admin_url('admin-ajax.php'));
    wp_localize_script('extra-script', 'my_postid', get_the_ID());
}

add_action('wp_ajax_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
add_action('wp_ajax_nopriv_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
function process_shortcode_on_click_ajax ()
{
    $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

    if (empty($post_id = $_POST['post_id']) || !is_numeric($post_id)) {
        wp_die('Post ID is Invalid', 400);
    }

    echo do_shortcode("[extra post_id='{$post_id}']");
    wp_die();
}

add_shortcode('extra', 't5_extra_content');
function t5_extra_content ($attributes, $content = '')
{
    $defaults = [
        'post_id' => get_the_ID(),
        'cap'     => 'edit_posts'
    ];

    $args = shortcode_atts($defaults, $attributes);

    if (!current_user_can($args['cap']) || empty($args['post_id'])) {
        return ''; // or some message on fail
    }

    return wpautop(get_post_meta($args['post_id'], '_t5_extra_box', TRUE) . $content);
}

推荐阅读