一次向帖子添加多个元密钥

时间:2015-12-04 作者:Iurie

我想出了如何将输入值作为元键值从前端帖子表单添加到新帖子中(感谢@thedeadmedic), 但我不明白how to add two or more meta keys at once. 下一个代码是否可以这样做?这些元键命名为“location2”和“price”,输入字段分别为“postLocation2”和“postPrice”(“验证后的$safe\\u price”)。

我的代码:

<?php
/*
 * Plugin Name: Submit From Front
 * Plugin URI: 
 * Description: This creates a form so that posts can be submitted from the front end.
 * Version: 0.1
 * Author: 
 * Author URI: 
 * Text Domain: submit-from-front
 */

class WPSE_Submit_From_Front {
    const NONCE_VALUE = \'front_end_new_post\';
    const NONCE_FIELD = \'fenp_nonce\';

    protected $pluginPath;
    protected $pluginUrl;
    protected $errors = array();
    protected $data = array();

    function __construct() {
        $this->pluginPath = plugin_dir_path( __file__ );
        $this->pluginUrl  = plugins_url( \'\', __file__ );
    }

    /**
     * Shortcodes should return data, NOT echo it.
     * 
     * @return string
     */
    function shortcode() {
        if ( ! current_user_can( \'publish_posts\' ) )
            return sprintf( \'<p>Please <a href="%s">login</a> to post adverts.</p>\', esc_url( wp_login_url(  get_permalink() ) ) );
        elseif ( $this->handleForm() )
            return \'<p class="success">Nice one, post created!</p>\';
        else
            return $this->getForm();
    }

    /**
     * Process the form and return true if post successfully created.
     * 
     * @return bool
     */
    function handleForm() {
        if ( ! $this->isFormSubmitted() )
            return false;

        // http://php.net/manual/en/function.filter-input-array.php
        $data = filter_input_array( INPUT_POST, array(
            \'postTitle\'   => FILTER_DEFAULT,
            \'postContent\' => FILTER_DEFAULT,
            \'postCategory\' => FILTER_DEFAULT,
            \'postLocation\' => FILTER_DEFAULT,
            \'postLocation2\' => FILTER_DEFAULT,
            \'postPrice\' => FILTER_DEFAULT,
        ));

        $data = wp_unslash( $data );
        $data = array_map( \'trim\', $data );

        // You might also want to more aggressively sanitize these fields
        // By default WordPress will handle it pretty well, based on the current user\'s "unfiltered_html" capability

        $data[\'postTitle\']   = sanitize_text_field( $data[\'postTitle\'] );
        $data[\'postContent\'] = wp_check_invalid_utf8( $data[\'postContent\'] );
        $data[\'postCategory\'] = sanitize_text_field( $data[\'postCategory\'] );
        $data[\'postLocation\'] = sanitize_text_field( $data[\'postLocation\'] );
        $data[\'postLocation2\'] = sanitize_text_field( $data[\'postLocation2\'] );
        $data[\'postPrice\'] = sanitize_text_field( $data[\'postPrice\'] );

        // Validate the Price field input
        $safe_price = intval( $data[\'postPrice\'] );
        if ( ! $safe_price ) {
            $safe_price = \'\';
        }

        if ( strlen( $safe_price ) > 10 ) {
            $safe_price = substr( $safe_price, 0, 10 );
        }

        $this->data = $data;

        if ( ! $this->isNonceValid() )
            $this->errors[] = \'Security check failed, please try again.\';

        if ( ! $data[\'postTitle\'] )
            $this->errors[] = \'Please enter a title.\';

        if ( ! $data[\'postContent\'] )
            $this->errors[] = \'Please enter the content.\';

        if ( ! $data[\'postCategory\'] )
            $this->errors[] = \'Please select a category.\';

        if ( ! $data[\'postLocation\'] )
            $this->errors[] = \'Please select a location.\';

        if ( ! $this->errors ) {
            $post_id = wp_insert_post( array(
                \'post_title\'   => $data[\'postTitle\'],
                \'post_content\' => $data[\'postContent\'],
                \'post_category\' => array( $data[\'postCategory\'] ),
                \'tax_input\' => array(\'loc\' => array( $data[\'postLocation\'] )),
                \'post_status\'  => \'publish\',
            ));

            // This will add a meta key \'location2\' to the post
            // How to add a second (the $safe_price value) meta key named \'price\'?
            $post_id = add_post_meta($post_id, \'location2\', $data[\'postLocation2\']);

            if ( ! $post_id )
                $this->errors[] = \'Whoops, please try again.\';
        } else {
            $post_id = 0;
        }

        return ( bool ) $post_id;
    }

    /**
     * Use output buffering to *return* the form HTML, not echo it.
     * 
     * @return string
     */
    function getForm() {
        ob_start();
        ?>

<div id ="frontpostform">
    <?php foreach ( $this->errors as $error ) : ?>

        <p class="error"><?php echo $error ?></p>

    <?php endforeach ?>

    <form id="formpost" method="post">
        <fieldset>
            <label for="postTitle">Post Title</label>
            <input type="text" name="postTitle" id="postTitle" value="<?php

                // "Sticky" field, will keep value from last POST if there were errors
                if ( isset( $this->data[\'postTitle\'] ) )
                    echo esc_attr( $this->data[\'postTitle\'] );

            ?>" />
        </fieldset>

        <fieldset>
            <label for="postContent">Content</label>
            <textarea name="postContent" id="postContent" rows="10" cols="35" ><?php

                if ( isset( $this->data[\'postContent\'] ) )
                    echo esc_textarea( $this->data[\'postContent\'] );

            ?></textarea>
        </fieldset>

        <!-- Category -->
        <fieldset>
            <label for="postCategory">Category</label>
            <select name="postCategory"> 
                <option value=""><?php echo esc_attr(__(\'Select Category\')); ?></option>
                <?php
                $categories = get_categories( \'hide_empty=0\' );
                foreach ($categories as $category) {
                    // keep post category value from last POST if there were errors
                    if ( isset( $this->data[\'postCategory\'] ) && $this->data[\'postCategory\'] == $category->cat_ID ) {
                       $option = \'<option value="\' . $category->cat_ID . \'" selected="selected">\';
                    } else {
                       $option = \'<option value="\' . $category->cat_ID . \'">\';
                    }
                    $option .= $category->cat_name;
                    $option .= \' (\'.$category->category_count.\')\';
                    $option .= \'</option>\';
                    echo $option;
                }
                ?>
            </select>
        </fieldset>

        <!-- Location -->
        <fieldset>
            <label for="postLocation">Location</label>
            <select name="postLocation"> 
                <option value=""><?php echo esc_attr(__(\'Select Location\')); ?></option>
                <?php
                $categories = get_terms( \'loc\', \'hide_empty=0\' );
                foreach ($categories as $category) {
                    if ( isset( $this->data[\'postLocation\'] ) && $this->data[\'postLocation\'] == $category->term_id ) {
                       $option = \'<option value="\' . $category->term_id . \'" selected="selected">\';
                    } else {
                       $option = \'<option value="\' . $category->term_id . \'">\';
                    }
                    $option .= $category->name;
                    $option .= \' (\'.$category->count.\')\';
                    $option .= \'</option>\';
                    echo $option;
                }
                ?>
            </select>
        </fieldset>

        <!-- Second Location -->
        <fieldset>
            <label for="postLocation2">Location 2</label>
            <input type="text" name="postLocation2" id="postLocation2" value="<?php

                // "Sticky" field, will keep value from last POST if there were errors
                if ( isset( $this->data[\'postLocation2\'] ) )
                    echo esc_attr( $this->data[\'postLocation2\'] );

            ?>" />
        </fieldset>

        <!-- Price -->
        <fieldset>
            <label for="postPrice">Price</label>
            <input type="text" name="postPrice" id="postPrice" maxlength="10" value="<?php

                // "Sticky" field, will keep value from last POST if there were errors
                if ( isset( $this->data[\'postPrice\'] ) )
                    echo esc_attr( $this->data[\'postPrice\'] );

            ?>" />
        </fieldset>

        <fieldset>
            <button type="submit" name="submitForm" >Create Post</button>
        </fieldset>

        <?php wp_nonce_field( self::NONCE_VALUE , self::NONCE_FIELD ) ?>
    </form>
</div>

        <?php
        return ob_get_clean();
    }

    /**
     * Has the form been submitted?
     * 
     * @return bool
     */
    function isFormSubmitted() {
        return isset( $_POST[\'submitForm\'] );
    }

    /**
     * Is the nonce field valid?
     * 
     * @return bool
     */
    function isNonceValid() {
        return isset( $_POST[ self::NONCE_FIELD ] ) && wp_verify_nonce( $_POST[ self::NONCE_FIELD ], self::NONCE_VALUE );
    }
}

new WPSE_Submit_From_Front;

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

正如@milo在上面所评论的,我希望保存为post-meta的每个值都需要它自己的调用update_post_meta. 因为$post_id 变量将返回新帖子的ID,这足够了,而不是:

$post_id = add_post_meta($post_id, \'location2\', $data[\'postLocation2\']);
要为每个所需的值插入:

add_post_meta($post_id, \'location2\', $data[\'postLocation2\']);
然后:

add_post_meta($post_id, \'price\', $safe_price);

SO网友:mrbobbybryant

正如@milo在上面所说的,您希望另存为post meta的每个值都需要它自己的调用来更新\\u post\\u meta。每次使用update\\u post\\u meta都需要您为该meta值指定一个唯一的名称。

由于您拥有一个数组中的所有数据,并且已经对其进行了清理,因此可以执行以下操作:

foreach( $data as $key => $value ) {
  update_post_meta( $post_id, $key, $value );
}
这将在数组中循环并保存每个值,并将“元键/名称”设置为之前在代码中设置的数组键。

因此,这应该对您有用,但我想说的是,在循环通过数据数组之前,可能需要更多地查看您的代码,以确保所有数据都存在。

相关推荐

是否可以取消对特定帖子类型的POSTS_PER_PAGE限制?

我想知道我是否可以取消特定帖子类型的posts\\u per\\u页面限制。在存档中。php页面我显示不同的帖子类型,对于特定的“出版物”帖子类型,我想显示所有帖子。我如何在不影响传统“post”类型的情况下实现这一点?