用于创建带有预览的自定义帖子的前端表单

时间:2018-08-15 作者:Alt C

如何实现带有预览选项的前端表单,以根据输入创建自定义帖子?我希望它没有任何插件完成。一个简单的例子会很有帮助


这不是ACF问题,但ACF具有前端表单功能,但没有预览功能。

是否可以获取正在填写的表单的id,以便将其传递给

get_preview_post_link( int|WP_Post $post = null, array $query_args = array(), string $preview_link = \'\' ) 
它尝试获取get\\u the\\u ID(),但它添加了表单所在页面的ID。另外,在生成表单字段后生成的页面id。

该表单适用于已注册和已登录的用户。也许,如果我能够得到一个解决方案,以获得该表单生成的帖子的id,我将是一个很好的位置来进一步。但问题是表单在提交后会生成ID,因此我无法传递以获取\\u preview\\u post\\u link()

谢谢

4 个回复
最合适的回答,由SO网友:filipecsweb 整理而成

有很多方法可以用来实现你的目标。这里有一个。。。

Steps:

<创建一个呈现表单的快捷码

In your functions.php:

/**
 * @return  string  $html   HTML form.
 */
function shortcode__new_post_form() {
    /**
     * @var     WP_User $current_user
     */
    $current_user = $GLOBALS[\'current_user\'];

    ob_start(); ?>
    <form action="" id="form-new-post">
        <fieldset>
            <legend>NEW AWESOME POST</legend>
            <div class="form-group">
                <input type="text" class="form-control" name="post_title" required/>
            </div>
            <input type="hidden" name="ID" value=""/>
            <input type="hidden" name="post_author" value="<?php echo $current_user->ID; ?>"/>
            <button type="submit"
                    class="submit"
                    data-is-updated="false"
                    data-is-update-text="UPDATE">CREATE
            </button>
        </fieldset>
        <a href=""
           class="preview-link"
           target="_blank"
           style="display: none;"
           rel="nofollow">Preview Link</a>
    </form>
    <?php
    $html = ob_get_clean();

    return $html;
}

function script__new_post_form() {
    wp_enqueue_script(
        \'new-post-form\',
        // Insert here your JavaScript file URL,
        array( \'jquery\' ),
        \'1.0.0\',
        true
    );

    wp_localize_script(
        \'new-post-form\',
        \'localized_new_post_form\',
        array(
            \'admin_ajax_url\' => admin_url( \'admin-ajax.php\' ),
        )
    );
}

function maybe_insert_new_post() {
    /**
     * @var     array $r Initialize response variable.
     */
    $r = array(
        \'error\'        => \'\', // Error message.
        \'html\'         => \'\', // Any message/HTML you want to output to the logged in user.
        \'preview_link\' => \'\', // Preview link URL.
        \'post\'         => \'\' // The created/updated post.
    );

    /**
     * @link    https://developer.wordpress.org/reference/functions/wp_insert_post/
     */
    $postarr = array(
        \'ID\'          => \'\', // If ID stays empty the post will be created.
        \'post_author\' => \'\',
        \'post_title\'  => \'My name is Optimus Prime\',
        \'post_status\' => \'draft\',
        \'post_type\'   => \'post\',
        \'meta_input\'  => array( // Delete this line if you won\'t use it!
            \'your_NON_acf_meta_field_key\' => \'your_NON_acf_meta_field_value\'
        )
    );

    parse_str( $_POST[\'form_data\'], $form_data );

    $postarr = array_merge( $postarr, $form_data );

    /**
     * wp_insert_post can either create posts or update existing ones, if ID is passed!
     *
     * @link    https://developer.wordpress.org/reference/functions/wp_insert_post/
     *
     * @param   array $postarr An array of elements that make up a post to update or insert.
     * @param   bool $wp_error Whether to return a WP_Error on failure.
     *
     * @return  int|WP_Error    The post ID on success. The value 0 or WP_Error on failure.
     */
    $new_post = wp_insert_post(
        $postarr,
        true
    );

    // Post was not created/updated, so let\'s output the error message.
    if ( is_wp_error( $new_post ) ) {
        $r[\'error\'] = $new_post->get_error_message();

        echo json_encode( $r );

        exit;
    }

    $post_id = $new_post; // Just for reference.

    /**
     * To save ACF fields use update_field() function. It doesn\'t matter if it\'s text field, repeater field, etc.
     * Make sure the field exists in admin area.
     * Use update_field() as many times as you want.
     *
     * @link    https://www.advancedcustomfields.com/resources/update_field/
     */
    update_field( \'your_acf_meta_key\', \'field_value\', $post_id );
//  update_field( \'your_acf_meta_key\', \'field_value\', $post_id );
//  update_field( \'your_acf_meta_key\', \'field_value\', $post_id );

    /**
     * @link    https://developer.wordpress.org/reference/functions/get_preview_post_link/
     */
    $preview_link = get_preview_post_link( $post_id );

    if ( $preview_link ) {
        $r[\'preview_link\'] = $preview_link;
    }

    // Gets post info in array format as it\'s easier to debug via console if needed.
    $post_array = get_post( $post_id, ARRAY_A );

    if ( $post_array ) {
        $r[\'post\'] = $post_array;
    }

    echo json_encode( $r );

    exit;
}

// Ads shortcode so you can use the form anywhere you want.
add_shortcode( \'new_post_form\', \'shortcode__new_post_form\' );

// Use wp_enqueue_scripts action hook so you can correctly localize the script with admin ajax URL.
add_action( \'wp_enqueue_scripts\', \'script__new_post_form\' );

// Prefix \'wp_ajax_\' is mandatory.
add_action( \'wp_ajax_new_post\', \'maybe_insert_new_post\' );

Create a JavaScript file and write in it (don\'t forget to put its URL in your functions.php):

(function ($) {

    var el_form = $(\'#form-new-post\'),
        el_form_submit = $(\'.submit\', el_form);

    // Fires when the form is submitted.
    el_form.on(\'submit\', function (e) {
        e.preventDefault();

        el_form_submit.attr(\'disabled\', \'disabled\');

        new_post();
    });

    // Ajax request.
    function new_post() {
        $.ajax({
            url: localized_new_post_form.admin_ajax_url,
            type: \'POST\',
            dataType: \'json\',
            data: {
                action: \'new_post\', // Set action without prefix \'wp_ajax_\'.
                form_data: el_form.serialize()
            },
            cache: false
        }).done(function (r) {
            if (r.post !== \'\' && r.preview_link !== \'\') {
                $(\'[name="ID"]\', el_form).attr(\'value\', r.post.ID);
                $(\'.preview-link\', el_form)
                    .attr(\'href\', r.preview_link)
                    .show();
                el_form_submit.attr(\'data-is-updated\', \'true\');
                el_form_submit.text(el_form_submit.data(\'is-update-text\'));
            }

            el_form_submit.removeAttr(\'disabled\');
        });
    }

    // Used to trigger/simulate post submission without user action.
    function trigger_new_post() {
        el_form.trigger(\'submit\');
    }

    // Sets interval so the post the can be updated automatically provided that it was already created.
    setInterval(function () {
        if (el_form_submit.attr(\'data-is-updated\') === \'false\') {
            return false;
        }

        trigger_new_post();
    }, 5000); // Set to 5 seconds.

})(jQuery);
现在,创建一个新页面并插入短代码[new_post_form] 在里面。打开页面并测试表单。

If it works for you, please accept my answer as your solution.

SO网友:Serkan Algur

您需要创建作为草稿发布以供预览。您可以使用此表单、函数和ajax脚本来实现此目的。

新岗位第一标准表;

<form method="post" id="new_post_form">
    <input type="text" name="post_title" id="title" />
    <?php
    /**
     * Simple editor for test reasons
     */ 
        wp_editor( \'\', \'post_content\' );
    ?>
    <input type="hidden" name="author_id" value="<?php echo get_current_user_id(); ?>" />
    <input type="text" name="security" value="<?php echo wp_create_nonce( "ajax_securiy_nonce" ); ?>">
    <input type="hidden" name="action" value="post_new_thing">
    <input type="submit" id="submit_preview" value="Submit & Preview" />
</form>
我们将使用ajax进行发布。因此,您需要一个ajax PHP函数来实现这一点。您可以在functions.php

function add_header_ajax_url(){
    echo \'<script type="text/javascript">var ajaxurl = "<?php echo admin_url("admin-ajax.php"); ?>";</script>\';
}

add_action( \'wp_head\', \'add_header_ajax_url\');

add_action( \'wp_ajax_post_new_thing\', \'post_new_thing\' );

function post_new_thing() {
    /**
     * Post new for post type
     */
    check_ajax_referer( \'ajax_securiy_nonce\', \'security\' );

    $title     = sanitize_text_field( $_POST[\'post_title\'] );
    $content   = sanitize_text_field( $_POST[\'post_content\'] );
    $author_id = sanitize_text_field( $_POST[\'author_id\'] );

    $args = array(
        \'post_title\'   => $title,
        \'post_content\' => $content,
        \'post_type\'    => \'post\',
        \'author\'       => $author_id,
        \'post_status\'  => \'draft\',
    );

    $posts = wp_insert_post( $args );


    if( is_wp_error( $posts ) ){
        echo json_encode( $posts->get_error_messages() );
    } else {
        if ( !function_exists( \'get_preview_post_link\' ) ) { 
            require_once ABSPATH . WPINC . \'/link-template.php\'; 
        } 
        $post_preview = get_preview_post_link($posts);
        echo $post_preview;
    }
    wp_die();
}
此函数用于返回预览链接。同时创建状态为草稿的帖子。我们将强制返回函数在新选项卡中打开预览。在需要的地方使用函数(可能在页脚中)。

<script type="text/javascript">
    jQuery(document).ready(function($){
        $(\'#submit_preview\').submit(function(e){
            $.ajax({
                type: \'post\',
                url : ajaxurl,
                data : $(\'#new_post_form\').serialize(),
                success : function(data){
                    window.open(data,\'_blank\');
                }
            });
            e.preventDefault();
        });
    });
</script>
该代码应按预期工作。如果代码有效或无效,请注释我。

SO网友:Aurovrata

如何实现带有预览选项的前端表单,以根据输入创建自定义帖子?我希望它没有任何插件完成。

没有插件是不可能的,除非你要做大量的自定义编码,这相当于得到一个插件。

不使用插件就可以实现这一点的唯一方法是使用WP中已有的后期创建/预览机制,即管理仪表板。使用插件,如Adminimize 微调用户的权限或为其创建新的自定义角色,允许他们创建新帖子并从后端仪表板查看帖子,但限制/删除其他仪表板菜单项,以便他们只能访问所需内容。

SO网友:Nathan Powell

选择你认为最适合你的后一种形式。然后使用WordPress的插件API创建它,或者学习可用的语言。如果要决定API,在Google上搜索WordPress表单会很有帮助。

有很多,所以你自己决定哪一个是适合你的。

结束

相关推荐

linking pic previews to posts

该网站是一个关于212个孩子的主题,位于www.travelwithcastle。com公司我想将帖子预览(主页上)上的图片链接到实际帖子——现在,当我单击图片时,它没有链接。仅链接标题文本。我喜欢这样,我还想链接图片预览。有人知道我怎么做吗?我的猜测是,这与我如何在内容中编写永久链接有关。php文件,但我不能对此发誓。为此,我的内容如下。php代码的当前外观。<?php /** * The default template for displaying content. Used

用于创建带有预览的自定义帖子的前端表单 - 小码农CODE - 行之有效找到问题解决它

用于创建带有预览的自定义帖子的前端表单

时间:2018-08-15 作者:Alt C

如何实现带有预览选项的前端表单,以根据输入创建自定义帖子?我希望它没有任何插件完成。一个简单的例子会很有帮助


这不是ACF问题,但ACF具有前端表单功能,但没有预览功能。

是否可以获取正在填写的表单的id,以便将其传递给

get_preview_post_link( int|WP_Post $post = null, array $query_args = array(), string $preview_link = \'\' ) 
它尝试获取get\\u the\\u ID(),但它添加了表单所在页面的ID。另外,在生成表单字段后生成的页面id。

该表单适用于已注册和已登录的用户。也许,如果我能够得到一个解决方案,以获得该表单生成的帖子的id,我将是一个很好的位置来进一步。但问题是表单在提交后会生成ID,因此我无法传递以获取\\u preview\\u post\\u link()

谢谢

4 个回复
最合适的回答,由SO网友:filipecsweb 整理而成

有很多方法可以用来实现你的目标。这里有一个。。。

Steps:

<创建一个呈现表单的快捷码

In your functions.php:

/**
 * @return  string  $html   HTML form.
 */
function shortcode__new_post_form() {
    /**
     * @var     WP_User $current_user
     */
    $current_user = $GLOBALS[\'current_user\'];

    ob_start(); ?>
    <form action="" id="form-new-post">
        <fieldset>
            <legend>NEW AWESOME POST</legend>
            <div class="form-group">
                <input type="text" class="form-control" name="post_title" required/>
            </div>
            <input type="hidden" name="ID" value=""/>
            <input type="hidden" name="post_author" value="<?php echo $current_user->ID; ?>"/>
            <button type="submit"
                    class="submit"
                    data-is-updated="false"
                    data-is-update-text="UPDATE">CREATE
            </button>
        </fieldset>
        <a href=""
           class="preview-link"
           target="_blank"
           style="display: none;"
           rel="nofollow">Preview Link</a>
    </form>
    <?php
    $html = ob_get_clean();

    return $html;
}

function script__new_post_form() {
    wp_enqueue_script(
        \'new-post-form\',
        // Insert here your JavaScript file URL,
        array( \'jquery\' ),
        \'1.0.0\',
        true
    );

    wp_localize_script(
        \'new-post-form\',
        \'localized_new_post_form\',
        array(
            \'admin_ajax_url\' => admin_url( \'admin-ajax.php\' ),
        )
    );
}

function maybe_insert_new_post() {
    /**
     * @var     array $r Initialize response variable.
     */
    $r = array(
        \'error\'        => \'\', // Error message.
        \'html\'         => \'\', // Any message/HTML you want to output to the logged in user.
        \'preview_link\' => \'\', // Preview link URL.
        \'post\'         => \'\' // The created/updated post.
    );

    /**
     * @link    https://developer.wordpress.org/reference/functions/wp_insert_post/
     */
    $postarr = array(
        \'ID\'          => \'\', // If ID stays empty the post will be created.
        \'post_author\' => \'\',
        \'post_title\'  => \'My name is Optimus Prime\',
        \'post_status\' => \'draft\',
        \'post_type\'   => \'post\',
        \'meta_input\'  => array( // Delete this line if you won\'t use it!
            \'your_NON_acf_meta_field_key\' => \'your_NON_acf_meta_field_value\'
        )
    );

    parse_str( $_POST[\'form_data\'], $form_data );

    $postarr = array_merge( $postarr, $form_data );

    /**
     * wp_insert_post can either create posts or update existing ones, if ID is passed!
     *
     * @link    https://developer.wordpress.org/reference/functions/wp_insert_post/
     *
     * @param   array $postarr An array of elements that make up a post to update or insert.
     * @param   bool $wp_error Whether to return a WP_Error on failure.
     *
     * @return  int|WP_Error    The post ID on success. The value 0 or WP_Error on failure.
     */
    $new_post = wp_insert_post(
        $postarr,
        true
    );

    // Post was not created/updated, so let\'s output the error message.
    if ( is_wp_error( $new_post ) ) {
        $r[\'error\'] = $new_post->get_error_message();

        echo json_encode( $r );

        exit;
    }

    $post_id = $new_post; // Just for reference.

    /**
     * To save ACF fields use update_field() function. It doesn\'t matter if it\'s text field, repeater field, etc.
     * Make sure the field exists in admin area.
     * Use update_field() as many times as you want.
     *
     * @link    https://www.advancedcustomfields.com/resources/update_field/
     */
    update_field( \'your_acf_meta_key\', \'field_value\', $post_id );
//  update_field( \'your_acf_meta_key\', \'field_value\', $post_id );
//  update_field( \'your_acf_meta_key\', \'field_value\', $post_id );

    /**
     * @link    https://developer.wordpress.org/reference/functions/get_preview_post_link/
     */
    $preview_link = get_preview_post_link( $post_id );

    if ( $preview_link ) {
        $r[\'preview_link\'] = $preview_link;
    }

    // Gets post info in array format as it\'s easier to debug via console if needed.
    $post_array = get_post( $post_id, ARRAY_A );

    if ( $post_array ) {
        $r[\'post\'] = $post_array;
    }

    echo json_encode( $r );

    exit;
}

// Ads shortcode so you can use the form anywhere you want.
add_shortcode( \'new_post_form\', \'shortcode__new_post_form\' );

// Use wp_enqueue_scripts action hook so you can correctly localize the script with admin ajax URL.
add_action( \'wp_enqueue_scripts\', \'script__new_post_form\' );

// Prefix \'wp_ajax_\' is mandatory.
add_action( \'wp_ajax_new_post\', \'maybe_insert_new_post\' );

Create a JavaScript file and write in it (don\'t forget to put its URL in your functions.php):

(function ($) {

    var el_form = $(\'#form-new-post\'),
        el_form_submit = $(\'.submit\', el_form);

    // Fires when the form is submitted.
    el_form.on(\'submit\', function (e) {
        e.preventDefault();

        el_form_submit.attr(\'disabled\', \'disabled\');

        new_post();
    });

    // Ajax request.
    function new_post() {
        $.ajax({
            url: localized_new_post_form.admin_ajax_url,
            type: \'POST\',
            dataType: \'json\',
            data: {
                action: \'new_post\', // Set action without prefix \'wp_ajax_\'.
                form_data: el_form.serialize()
            },
            cache: false
        }).done(function (r) {
            if (r.post !== \'\' && r.preview_link !== \'\') {
                $(\'[name="ID"]\', el_form).attr(\'value\', r.post.ID);
                $(\'.preview-link\', el_form)
                    .attr(\'href\', r.preview_link)
                    .show();
                el_form_submit.attr(\'data-is-updated\', \'true\');
                el_form_submit.text(el_form_submit.data(\'is-update-text\'));
            }

            el_form_submit.removeAttr(\'disabled\');
        });
    }

    // Used to trigger/simulate post submission without user action.
    function trigger_new_post() {
        el_form.trigger(\'submit\');
    }

    // Sets interval so the post the can be updated automatically provided that it was already created.
    setInterval(function () {
        if (el_form_submit.attr(\'data-is-updated\') === \'false\') {
            return false;
        }

        trigger_new_post();
    }, 5000); // Set to 5 seconds.

})(jQuery);
现在,创建一个新页面并插入短代码[new_post_form] 在里面。打开页面并测试表单。

If it works for you, please accept my answer as your solution.

SO网友:Serkan Algur

您需要创建作为草稿发布以供预览。您可以使用此表单、函数和ajax脚本来实现此目的。

新岗位第一标准表;

<form method="post" id="new_post_form">
    <input type="text" name="post_title" id="title" />
    <?php
    /**
     * Simple editor for test reasons
     */ 
        wp_editor( \'\', \'post_content\' );
    ?>
    <input type="hidden" name="author_id" value="<?php echo get_current_user_id(); ?>" />
    <input type="text" name="security" value="<?php echo wp_create_nonce( "ajax_securiy_nonce" ); ?>">
    <input type="hidden" name="action" value="post_new_thing">
    <input type="submit" id="submit_preview" value="Submit & Preview" />
</form>
我们将使用ajax进行发布。因此,您需要一个ajax PHP函数来实现这一点。您可以在functions.php

function add_header_ajax_url(){
    echo \'<script type="text/javascript">var ajaxurl = "<?php echo admin_url("admin-ajax.php"); ?>";</script>\';
}

add_action( \'wp_head\', \'add_header_ajax_url\');

add_action( \'wp_ajax_post_new_thing\', \'post_new_thing\' );

function post_new_thing() {
    /**
     * Post new for post type
     */
    check_ajax_referer( \'ajax_securiy_nonce\', \'security\' );

    $title     = sanitize_text_field( $_POST[\'post_title\'] );
    $content   = sanitize_text_field( $_POST[\'post_content\'] );
    $author_id = sanitize_text_field( $_POST[\'author_id\'] );

    $args = array(
        \'post_title\'   => $title,
        \'post_content\' => $content,
        \'post_type\'    => \'post\',
        \'author\'       => $author_id,
        \'post_status\'  => \'draft\',
    );

    $posts = wp_insert_post( $args );


    if( is_wp_error( $posts ) ){
        echo json_encode( $posts->get_error_messages() );
    } else {
        if ( !function_exists( \'get_preview_post_link\' ) ) { 
            require_once ABSPATH . WPINC . \'/link-template.php\'; 
        } 
        $post_preview = get_preview_post_link($posts);
        echo $post_preview;
    }
    wp_die();
}
此函数用于返回预览链接。同时创建状态为草稿的帖子。我们将强制返回函数在新选项卡中打开预览。在需要的地方使用函数(可能在页脚中)。

<script type="text/javascript">
    jQuery(document).ready(function($){
        $(\'#submit_preview\').submit(function(e){
            $.ajax({
                type: \'post\',
                url : ajaxurl,
                data : $(\'#new_post_form\').serialize(),
                success : function(data){
                    window.open(data,\'_blank\');
                }
            });
            e.preventDefault();
        });
    });
</script>
该代码应按预期工作。如果代码有效或无效,请注释我。

SO网友:Aurovrata

如何实现带有预览选项的前端表单,以根据输入创建自定义帖子?我希望它没有任何插件完成。

没有插件是不可能的,除非你要做大量的自定义编码,这相当于得到一个插件。

不使用插件就可以实现这一点的唯一方法是使用WP中已有的后期创建/预览机制,即管理仪表板。使用插件,如Adminimize 微调用户的权限或为其创建新的自定义角色,允许他们创建新帖子并从后端仪表板查看帖子,但限制/删除其他仪表板菜单项,以便他们只能访问所需内容。

SO网友:Nathan Powell

选择你认为最适合你的后一种形式。然后使用WordPress的插件API创建它,或者学习可用的语言。如果要决定API,在Google上搜索WordPress表单会很有帮助。

有很多,所以你自己决定哪一个是适合你的。

相关推荐

linking pic previews to posts

该网站是一个关于212个孩子的主题,位于www.travelwithcastle。com公司我想将帖子预览(主页上)上的图片链接到实际帖子——现在,当我单击图片时,它没有链接。仅链接标题文本。我喜欢这样,我还想链接图片预览。有人知道我怎么做吗?我的猜测是,这与我如何在内容中编写永久链接有关。php文件,但我不能对此发誓。为此,我的内容如下。php代码的当前外观。<?php /** * The default template for displaying content. Used