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

标签 javascript php jquery ajax wordpress

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

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

简单模型:

enter image description here

对于创建子帖子,我可以使用这个:

$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。 有人对此有想法吗?

最佳答案

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

所以你可以做的是获取变量和print it into the HTML body like described in this answer ,像这样使用 admin_footer Hook :

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 调用中。

关于javascript - 为 WordPress 自定义帖子类型创建动态子帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35183151/

相关文章:

javascript - Map 和 Set 有什么区别?

php - SMTP 服务器响应 : 501 <>: missing or malformed local part

javascript - 如何编写一个 jQuery 事件来显示双击时的表单,而该表单不会对双击事件使用react?

jquery - onClick 使用 jQuery .animate 转到页面底部

javascript - jquery datepicker在不同浏览器上有不同的格式

javascript - 使用单个函数隐藏多个输入

javascript - 如何在不发布表单的情况下获取文本字段的值

javascript - 为什么我在使用 map 和 ES6 模板的 html 输出的开头得到 ,

php - 存在未知列的 MySQL 警告

php - 我如何获取 ?> 和 <?php 之间的内容