前端帖子创建插件疑难解答(API帖子请求)

时间:2019-03-24 21:57:45

标签: wordpress api plugins

我目前正在为wordpress构建一个插件,该插件应允许用户从其网站的前端创建新帖子。当我单击创建帖子按钮时,没有任何反应。请在下面查看我的代码:

该插件使用带有pHp的JavaScript函数向API发出POST请求。我在本地服务器(MAMP)上工作,目前不使用漂亮的永久链接,因此我的网址看起来像这样... http://localhost:9000/wordpress/?rest_route=/wp/v2/posts 我访问过并看到了JSON数据。我似乎可以按一下按钮来发出实际的发帖请求。

php / html

// Make sure we don't expose any info if called directly
if ( !function_exists( 'add_action' ) ) {
    echo 'Hi there!  I\'m just a plugin, not much I can do when called directly.';
    exit;
}


function postayge_front()
{
    /* content variable */
    $content = '';

    $content .= '<div class="admin-quick-add">';

    $content .= '<h3>Quick Add Post</h3>';

    $content .= '<input type="text" name="title" placeholder="Title">';
    $content .= '<textarea name="content" placeholder="Content"></textarea>';
    $content .= '<button id="quick-add-button">Create Post</button>';

    $content .= '</div>';

        return $content;
}

add_shortcode('postayge','postayge_front');



/* Add scripts & styles */
function wp_postayge_adding_styles() {
    wp_register_style('postayge_style', plugins_url('main.css', __FILE__));
    wp_enqueue_style('postayge_style');

    wp_register_script('postayge_script', plugins_url('script.js', __FILE__));
    wp_enqueue_script('postayge_script');

    wp_localize_script('script.js', 'securityData', array(
        'nonce' => wp_create_nonce('wp_rest')
    ));

    }

    add_action( 'wp_enqueue_scripts', 'wp_postayge_adding_styles' );  


?>

js

//Quick add post AJAX

var quickAddButton = document.querySelector("#quick-add-button");

if (quickAddButton) {
    quickAddButton.addEventListener("click", function() {
        var postaygePostData = {
            "title": document.querySelector('.admin-quick-add[name="title"]').value,
            "content": document.querySelector('.admin-quick-add[name="content"]').value,
            "status": "publish"
        }

        var createPost = new XMLHttpRequest();
        createPost.open("POST", "http://localhost:9000/wordpress/?rest_route=/wp/v2/posts");
        createPost.setRequestHeader("X-WP-Nonce", securityData.nonce);
        createPost.setRequestHeader("Content-Type", "applicaton/json;charset=UTF-8")
        createPost.send(JSON.stringify(postaygePostData));
    });
}

css

/** Quick Add Styles */
.admin-quick-add {
background-color: inherit;
padding:15px;
margin-bottom: 15px;
}

.admin-quick-add input,
.admin-quick-add textarea {
width: 100%;
border: none;
padding: 10px;
margin: 0 0 10px 0;
box-sizing: border-box;
}

0 个答案:

没有答案