【问题标题】:Create dynamic sub posts for a WordPress custom post type为 WordPress 自定义帖子类型创建动态子帖子
【发布时间】:2016-05-13 00:14:38
【问题描述】:

我现在计划一个简单的插件,我在帖子创建页面上搜索在 wordpress 中添加子帖子(子)的想法。

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

简单的模型:

为了创建子帖子,我可以使用这个:

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

【问题讨论】:

    标签: javascript php jquery ajax wordpress


    【解决方案1】:

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

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

    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']的if)

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

    【讨论】:

    • 谢谢!就是这样:)你救了我的命,谢谢你的回复:)
    猜你喜欢
    • 1970-01-01
    • 2020-06-06
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 2016-11-29
    相关资源
    最近更新 更多