为WordPress自定义帖子类型创建动态子帖子

时间:2016-02-03 16:58:36

标签: javascript php jquery ajax wordpress

我现在计划简单插件,我想在帖子创建页面上为wordpress中的帖子添加子帖子(child)。

我想添加包含两个字段,标题和内容的表单,并使用当前父帖子的父ID保存。

简单的模型:

enter image description here

对于create subpost我可以使用:

$post = array(
    'post_title'    => wp_strip_all_tags( $_POST['post_title'] ),
    'post_content'  => $_POST['post_content'],
    'post_status'   => 'publish',
    'post_parent'   => id of post
);
wp_insert_post($post);

但我想用ajax做这个动态,但在创建页面上我没有父帖子ID。 有人对此有想法吗?

1 个答案:

答案 0 :(得分:1)

实际上,你确实有一个帖子ID,它不在数据库或查询中。您可以在全局变量$wpdb中找到它。

所以你可以做的就是使用这个admin_footer钩子来取变量和print it into the HTML body like described in this answer

add_action('admin_footer', 'print_id_for_ajax');
function print_id_for_ajax() {
    $post_id = isset($_GET['post']) ? $_GET['post'] : $GLOBALS['wpdb']->insert_id;
    ?>
        <script>
            var post_id = <?php echo $post_id ?>;
        </script>
    <?php
}

(当然,只有在$_GET['post']未设置的情况下,如果该帖子尚未存在,我们是否要从$GLOBALS['wpdb']开始

将它放入主题的function.php文件中,现在您可以使用javascript中的post_id变量并将其传递给AJAX调用。

相关问题