如何用AJAX插件开发测试现时值

时间:2021-09-28 作者:upss1988

我构建了一个插件,但现在我不确定nonce 集成正确,我不知道如何测试它们。

有没有人能帮我测试一下,或者让我知道nonce 是否正确集成?

下面是我的代码中的一个示例:

PHP:

public function __construct() {
    if ( ! is_admin() ) {
        add_action( \'wp_head\', array( $this, \'pp_html_template\' ) );
        add_action( \'init\', array( $this, \'pp_html_process\' ) );
    }

    add_action( \'wp_ajax_pp_html_process\', array( $this, \'pp_html_process\' ) );
}

public function pp_html_template() {
    ?>
    <form id="pp-form-submit" name="pp-form-submit" class="pp-form-submit" enctype="multipart/form-data">
        <?php wp_nonce_field( \'pp_publisher_save\', \'pp_publisher_name\' ); ?>
        <div class="pp-row">
            <label for="pp-title"><?php esc_attr_e( \'Title\', \'post-publisher\' ) ?></label>
            <input type="text" id="pp-title" name="pp_title" required>
        </div>
    
        <div class="pp-row">
            <label for="pp-content"><?php esc_attr_e( \'Content\', \'post-publisher\' ) ?></label>
            <textarea id="pp-content" name="pp_content" cols="30" rows="10" required></textarea>
        </div>
    
        <div class="pp-row">
            <label for="pp-featured-image"><?php esc_attr_e( \'Featured Image\', \'post-publisher\' ) ?></label>
            <input type="file" id="pp-featured-image" name="pp_featured_image" required>
        </div>
        <input type="hidden" name="action" value="pp_html_process"/>
        <div class="pp-row">
            <input type="submit" name="pp_submit" id="pp-submit">
        </div>
    
        <div class="pp-row">
            <div id="pp-response"></div>
            <div class="pp-posts-area"></div>
        </div>
    </form>
<?php }

public function pp_html_process() {
    if ( isset( $_POST[\'pp_submit\'] ) ) {
        if ( ! isset( $_POST[\'pp_publisher_name\'] ) || ! wp_verify_nonce( $_POST[\'pp_publisher_name\'], \'pp_publisher_save\' ) ) {
            esc_attr__( \'Sorry, this action is not allowed.\', \'post-publisher\' );
            exit;
        } else {
            $inc = new Pp_Includes();
            $inc->pp_post_data(\'pp_title\', \'pp_content\', \'pp_featured_image\');

            global $current_user;

            $user_login   = $current_user->user_login;
            $user_id      = $current_user->ID;
            $post_title   = sanitize_text_field( $_POST[ \'pp_title\' ] );
            $post_content = sanitize_textarea_field( $_POST[ \'pp_content\' ] );

            $arg = array(
                \'post_title\'   => $post_title,
                \'post_content\' => $post_content,
                \'post_author\'  => $user_id,
                \'post_type\'    => \'post\',
                \'post_status\'  => \'draft\',
                \'post_name\'    => str_replace( \' \', \'-\', $post_title ),
            );

            $post_id = wp_insert_post( $arg, true );

            if ( ! function_exists( \'wp_generate_attachment_metadata\' ) ) {
                require_once( ABSPATH . "wp-admin" . \'/includes/image.php\' );
                require_once( ABSPATH . "wp-admin" . \'/includes/file.php\' );
                require_once( ABSPATH . "wp-admin" . \'/includes/media.php\' );
            }

            $featured_image = media_handle_upload( \'pp_featured_image\', $post_id );

            if ( is_wp_error( $featured_image ) ) {
                wp_die( $featured_image );
            }

            if ( $featured_image > 0 ) {
                update_post_meta( $post_id, \'_thumbnail_id\', $featured_image );
            }

            if ( wp_doing_ajax() ) {
                wp_die();
            }
        }
    }
}
以下是本地化脚本:

public function pp_enqueue_public_styles() {
    wp_enqueue_script( \'pp_public_ajax\', plugins_url( \'/assets/js/pp-public-ajax.js\', __FILE__ ), array( \'jquery\' ), null, true );
    wp_localize_script( \'pp_public_ajax\', \'pp_public_ajax\',
        array(
            \'pp_ajaxurl\'             => admin_url( \'admin-ajax.php\' ),
            \'pp_publisher_name\'      => wp_create_nonce( \'pp_publisher_save\' )
        )
    );
}
AJAX:

function ppAjaxSubmit() {
    var ppFormData = new FormData(this);

    ppFormData.append(\'pp_submit\', 1);
    ppFormData.append(\'security\', pp_public_ajax.pp_publisher_name)

    $.ajax({
        action: \'pp_featured_image\',
        type: \'POST\',
        url: pp_public_ajax.pp_ajaxurl,
        data: ppFormData,
        processData: false,
        contentType: false,
        success: function () {
            console.log(data);
        },
        error: function () {
            console.log(err)
        }
    });

    return false;
}

$(\'#pp-form-submit\').submit(ppAjaxSubmit);
如有任何建议,将不胜感激。

1 个回复
SO网友:Santiago Cerro López

我看到了一些问题:

ajax操作只能由登录用户使用。如果这是正确的,我建议您添加一个返回错误消息的nopriv操作

    // Inside Constructor    
    add_action( \'wp_ajax_nopriv_pp_html_process\', array( $this, \'pp_html_process_not_logged\' ) );

并创建此函数:

    public function pp_html_process_not_logged () {
        // Status can be used to identify via JS if the operation is OK or KO and print an error with jQuery or a modal window, whatever you prefer.
        wp_send_json([
            \'status\' => false,
            \'error\' => __(\'Error. This service is only for logged users.\', \'your_plugin_lang_slug\')
        ]);
    }
创建一个不会使用的wp\\u nonce字段(稍后在JS中创建其他同名/操作的字段)。在您的“中删除此行”;pp\\U html\\U模板;功能:
    <?php wp_nonce_field( \'pp_publisher_save\', \'pp_publisher_name\' ); ?>
  
wp\\u head在head标记内打印HTML,而这不是;“允许”;。此表单需要位于正文标记内。也许您可以将其添加到页脚中,或者更好的解决方案是使用add\\u shortcode函数创建一个短代码,并将该短代码放在您想要显示此表单的页面或帖子中。

删除构造函数中的这一行,因为在3中解释了原因,并且您正在创建一个AJAX操作,AJAX操作由wp\\u AJAX\\uu{$action}hook处理。

    if ( ! is_admin() ) {
        add_action( \'wp_head\', array( $this, \'pp_html_template\' ) );
        add_action( \'init\', array( $this, \'pp_html_process\' ) );
    }
确保;pp\\u enqueue\\u public\\u样式“;在“中调用”;wp\\U enqueue\\U脚本“;或“或”;admin\\u enqueue\\u脚本“;如果它只出现在仪表板上。如果您决定创建一个短代码,可以在窗体之前调用此函数。

在JS文件中更改以下行:

    ppFormData.append(\'pp_submit\', 1);
    ppFormData.append(\'security\', window.pp_public_ajax.pp_publisher_name)
    ppFormData.append(\'action\', \'pp_html_process\');
    
并删除AJAX函数中的这一行:

    action: \'pp_featured_image\',

您的;pp\\u enqueue\\u public\\u样式“;功能:
public function pp_enqueue_public_styles() {
    // Register the script first!!
    wp_register_script( \'pp_public_ajax\', plugins_url( \'/assets/js/pp-public-ajax.js\', __FILE__ ), array( \'jquery\' ), null, true );    
    wp_localize_script( \'pp_public_ajax\', \'pp_public_ajax\',
        array(
            \'pp_ajaxurl\'             => admin_url( \'admin-ajax.php\' ),
            \'pp_publisher_name\'      => wp_create_nonce( \'pp_publisher_save\' )
        )
    );
    wp_enqueue_script(\'pp_public_ajax\');
}

相关推荐

添加HTML代码以替换PHP中的文本

我想更改未登录用户的下载按钮。我想显示一个带有登录/注册消息的自定义HTML代码,而不是下载按钮。下面的代码隐藏了按钮,但新HTML代码的注入不起作用。<?php if (!is_user_logged_in()) : ?> <style> .product-purchase-box{ display: none; } </style> <script> <p>