web-dev-qa-db-ja.com

新しい投稿にデフォルトのmeta_valueを追加する

ユーザーがフロントエンドから投稿を作成および更新できるようにするページテンプレートがあります。私はまた2つのプラグインを使用しています。1つはユーザーが1-5の星から投稿を評価することを可能にし、もう1つはそれらが投稿をお気に入りにできるようにします。

私はまた、ユーザーが日付/カテゴリ/投稿タイプ/ etcで投稿を並べ替えることを切り替えることを可能にするページを持っています。あなたはここでページを見ることができます: http://www.theseattlevine.com/the-Vine/

問題は、私が投稿を星の評価またはお気に入りの数でソートした場合、Wordpressはそのメタ値を持つ投稿のみを返し、まだ受け取っていない投稿は表示されないということです。それが言われているので、私は2つのうち1つをする必要があります:

  1. 投稿が作成されたときにメタ値をデフォルト値に自動的に設定します。
  2. まだ値がない投稿も表示するようにwp_queryを変更します。

誰でも私がこれらのことのどちらかをすることができる方法を知っていますか?私は#1を好むが、どちらでもうまくいくだろう。

これが便利な場合は、ここにページテンプレートコードがあります。

        <?php

    /**
     * Template Name: New UserPost
     * 
     * A Page template for Submitting User Post   
     * 
     */
    if(!is_user_logged_in()){
        header("location:". esc_url(home_url('')));
        ?>
    <script type="text/javascript">
        window.location = '<?PHP echo esc_url(home_url('')); ?>';
    </script>
        <?PHP
        die('');
    }


    wp_enqueue_script('jquery');

    function add_header(){
        ?>
    <link rel="stylesheet" type="text/css" 
          href="<?PHP bloginfo('template_directory'); ?>/css/redmond/jquery-ui-1.9.1.custom.min.css" />
    <script type="text/javascript" src="<?PHP bloginfo('template_directory') ?>/js/jquery-ui-1.9.1.custom.min.js"></script>
    <script type="text/javascript" src="<?PHP bloginfo('template_directory'); ?>/fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
    <script type="text/javascript" src="<?PHP bloginfo('template_directory'); ?>/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
    <link rel="stylesheet" type="text/css" href="<?PHP bloginfo('template_directory'); ?>/fancybox/jquery.fancybox-1.3.4.css" media="screen" />
    <script type="text/javascript">
        function show_loading_div(){
            data="<p>Uploading your file, one moment...</p>";
            data+="<img src=\"<?PHP echo get_bloginfo('template_directory'); ?>/images/ajaxloading_bar.gif\" />";
            jQuery('#fancybox-frame').contents().find("#upload_frm").hide();
            jQuery('#fancybox-frame').contents().find("#MSG_DIV").html(data);
        }
        function get_featured_image(){

            if(jQuery('#featured_img_id').val()==-1){
                return;
            }
            jQuery('#featured_img_div').html('');
            jQuery.ajax({
                 url:'<?PHP echo get_permalink(); ?>',
                 data:"featured_img_id=" + jQuery('#featured_img_id').val() + "&req=get_featured_image",
                 beforeSend:function(){
                     jQuery('#featured_img_loading').show();
                 },complete:function(){
                     jQuery('#featured_img_loading').hide();
                 },success:function(data){
                     jQuery('#featured_img_div').html(data);
                 }
             }); 
        }
        jQuery().ready(function(){

            jQuery('.loading,#featured_img_action').hide();

            jQuery('#dialog_message').dialog({
                autoOpen:false,
                buttons:{
                    'Ok':function(){
                        jQuery(this).dialog('close');
                    }
                }
            });
            jQuery('#cancel_btn').click(function(){
                if(jQuery('#post_id').val()==-1){
                    jQuery('#dialog_message').html('Post has been discarded').dialog('option',{
                        buttons:{
                            'Ok':function(){
                               jQuery(this).html('One moment...');
                                window.location='<?PHP echo esc_url(home_url('dashboard/')); ?>'
                            }
                        }
                    }).dialog('open');
                }else{
                   jQuery.ajax({
                        url:'<?PHP echo get_permalink(); ?>',
                        data:jQuery('#tsv_user_post_form').serialize() + "&req=discard_post",
                        beforeSend:function(){
                            jQuery('#submit_loading').show();
                        },complete:function(){
                            jQuery('#submit_loading').hide();
                        },success:function(data){
                            jQuery('#exe').html(data);
                        }
                    }); 
                }
            })

            jQuery('#upload_img').click(function(){
               jQuery.fancybox({
                    'autoScale'     : true,
                    'transitionIn'  : 'none',
                    'transitionOut' : 'none',
                    'type'          : 'iframe',
                    'href'          : "<?PHP echo esc_url(home_url('image-upload')) ?>?post_id=" + jQuery('#post_id').val()+'&img_id=' + jQuery('#featured_img_id').val()  ,
                    'onClosed'      : function(){
                                        get_featured_image();
                                        if(jQuery('#featured_img_id').val()!=-1){
                                            jQuery('#featured_img_action').show()
                                        }
                                     }
                });
           });

            jQuery('#remove_image_btn').click(function(){

                jQuery.ajax({
                    url:'<?PHP echo esc_url(home_url('new-post')); ?>',
                    data:'req=delete_attach&aid=' + jQuery('#featured_img_id').val(),
                    beforeSend:function(){
                        jQuery('#featured_img_div').html('Deleting Image....');
                        jQuery('#featured_img_action').hide()
                    },
                    success:function(data){
                        jQuery('#featured_img_div').html('');
                        jQuery('#featured_img_id').val('-1');
                    },
                    complete:function(){
                        jQuery('#remove_image_btn').hide();
                    }
                })


            });

            jQuery('#user_post_submit,#user_post_preview,#user_post_savedraft').click(function(){
                var req;
                switch(jQuery(this).attr('id')){
                    case 'user_post_submit':
                        req='publish';
                        break;
                    case 'user_post_savedraft':
                        req='save_draft';
                        break;
                    case 'user_post_preview':
                        req='post_preview';
                        break;

                }
                jQuery.ajax({
                    url:'<?PHP echo get_permalink(); ?>',
                    data:jQuery('#tsv_user_post_form').serialize() + "&req=" + req,
                    beforeSend:function(){
                        jQuery('#submit_loading').show();
                    },complete:function(){
                        jQuery('#submit_loading').hide();
                    },success:function(data){
                        //alert(data);
                        jQuery('#exe').html(data);
                    }
                })
            })
        });
    </script>
        <?PHP
    }

    add_action('wp_head','add_header');
    switch($_REQUEST['req']){

        case 'delete_attach':

            $attachment_id = $_REQUEST['aid'];
            wp_delete_post($attachment_id,TRUE);
            die('');
            break;
        case 'discard_post':
            $post_id = $_REQUEST['post_id'];
            wp_delete_post($post_id,TRUE);
            ?>
       <script type="text/javascript">
       jQuery('#dialog_message').html('Post has been discarded').dialog('option',{
           buttons:{
               'Ok':function(){
                  jQuery(this).html('One moment...');
                   window.location='<?PHP echo esc_url(home_url('dashboard/')); ?>'
               }
           }
       }).dialog('open');
       </script>
            <?PHP
           die('');
           break;
       case 'get_featured_image':
           $featured_img = $_REQUEST['featured_img_id'];
           echo wp_get_attachment_image($featured_img, array(100,100));
           die('');
           break;
       case 'publish':
       case 'save_draft':
       case 'post_preview':


        $error_flag    = FALSE;
        $error_message = array();
        $post_id       = $_REQUEST['post_id'];
        $categories    = array($_REQUEST['cat']);
        $featured_img  = $_REQUEST['featured_img_id'];
        /**
         * Validation Step(s)
         */
        if(empty($_REQUEST['user_post_title'])){
            $error_flag = TRUE;
            $error_msg[]=array(
                'key'      => 'error_user_post_title',
                'value'    => __('Please enter a title','tsv'),
            );
        }elseif(strlen($_REQUEST['user_post_title'])>125){
            $error_flag = TRUE;
            $error_msg[]=array(
                'key'      => 'error_user_post_title',
                'value'    => __('Please enter a title with less then 125 characters','tsv'),
            );
        }
        if(empty($_REQUEST['user_post_summary'])){
            $error_flag = TRUE;
            $error_msg[]=array(
                'key'      => 'error_user_post_summary',
                'value'    => __('Please enter a short summary of the post','tsv'),
            );
        }elseif(strlen($_REQUEST['user_post_summary'])>250){
            $error_flag = TRUE;
            $error_msg[]=array(
                'key'      => 'error_user_post_summary',
                'value'    => __('Please enter a summary with less then 250 characters','tsv'),
            );
        }

        if(empty($_REQUEST['user_post_content'])){
            $error_flag = TRUE;
            $error_msg[]=array(
                'key'      => 'error_user_post_content',
                'value'    => __('Please enter some content','tsv'),
            );
        }

        if(empty($_REQUEST['cat']) || $_REQUEST['cat']==-1){
            $error_flag = TRUE;
            $error_msg[]=array(
                'key'      => 'error_cat',
                'value'    => __('Please choose a category','tsv'),
            );
        }

        if(count($error_msg)>0 && $error_flag){
            ?>
            <script type="text/javascript">
                jQuery('.error').html('').hide();
                var temp=<?PHP echo json_encode($error_msg); ?>;
                for(i=0;i<temp.length;i++)
                    jQuery('#' + temp[i].key ).show().html(temp[i].value);
                jQuery("html,body").animate({ scrollTop: 0 }, "slow");
            </script>
            <?PHP
        }else{
            $post_param = array(
                'post_content'   => $_REQUEST['user_post_content'],
                'post_title'     => $_REQUEST['user_post_title'],
                'post_excerpt'     => $_REQUEST['user_post_summary'],
                'post_type'      => 'tsv_userpost',
                'tax_input'      => array('category'=>$categories)
            );

            if(!empty($_REQUEST['user_post_tags'])){
                $post_param['tags_input'] = array_slice(explode(",", $_REQUEST['user_post_tags']),0,5);
            }

            if($post_id!=-1){
                $post_param['ID']=$post_id;
            }
            /**
             * Action Based on The Button Pressed
             */
            switch($_REQUEST['req']){
                case 'publish':
                    $post_param['post_status'] = 'publish';
                    $new_post_id=wp_insert_post($post_param);
                    ?>
                    <script type="text/javascript">
                        jQuery('#dialog_message').html('Post published succesfully!').dialog('option',{
                            buttons:{
                                'Ok':function(){
                                    jQuery(this).html('One moment....');
                                    window.location='<?PHP echo esc_url(home_url('dashboard')); ?>'
                                }
                            }
                        }).dialog('open');
                    </script>
                    <?PHP
                    break;
                case 'save_draft':

                     $post_param['post_status'] = 'draft';
                     $new_post_id=wp_insert_post($post_param);

                     ?>
                    <script type="text/javascript">
                        jQuery('#post_id').val('<?PHP echo $new_post_id; ?>')            
                        jQuery('#dialog_message').html('Post draft saved').dialog('option',{
                            buttons:{
                                'Ok':function(){
                                    jQuery(this).dialog('close');
                                }
                            }
                        }).dialog('open');
                    </script>
                    <?PHP
                    break;
                case 'post_preview':
                     $post_param['post_status'] = 'draft';
                     $new_post_id=wp_insert_post($post_param);
                     ?>
                    <script type="text/javascript">
                        jQuery('#post_id').val('<?PHP echo $new_post_id; ?>')            
                        //jQuery('#dialog_message').html('Loading preview, one moment...').dialog('open');
                        jQuery('#dialog_message').html('Please click Ok To load Preview').dialog('option',{buttons:{
                            'Ok':function(){
                                window.open('<?PHP echo esc_url(home_url('?page_id=' . $new_post_id . '&preview=true')); ?>');
                                jQuery(this).dialog('close');
                            }
                        }}).dialog('open');
                        /*jQuery('#preview_link').attr({'href':'<?PHP echo esc_url(home_url('?page_id=' . $new_post_id . '&preview=true')); ?>'})
                        jQuery('#preview_link')[0].click();*/

                        //window.open('<?PHP echo esc_url(home_url('?page_id=' . $new_post_id . '&preview=true')); ?>');
                    </script>
                    <?PHP
                    break;
            }

            if($featured_img!=-1){
                update_post_meta($new_post_id,'_thumbnail_id',$featured_img);
            }else{
                delete_post_meta($new_post_id,'_thumbnail_id');
            }
        }
        die('');
        break;
    }

    global $current_user;
    get_currentuserinfo();

    if(isset($_GET['post_id'])){
        $post_id  = $_GET['post_id'];
        $post_obj = get_post($post_id);
        if($post_obj->post_author!=$current_user->ID){
            header("location:" . esc_url(home_url('')));
            die('');
        }else{
            $featured_img_id = get_post_meta($post_id,'_thumbnail_id',TRUE);
            if(empty($featured_img_id)){
                $featured_img_id = -1;
            }
        }
    }else{
        $post_id = -1; // -1 Will be for New Post
        $featured_img_id = -1;
    }


    get_header();
    ?>
            <section id="primary">
                <div id="content" role="main"> 
                    <?php userpost_menu(); ?>



    <form action="" method="post" name="" id="tsv_user_post_form" enctype="multipart/form-data" >
        <input placeholder="Enter Your Title..." type="text" 
               value="<?PHP echo ((!empty($post_obj->post_title))?$post_obj->post_title:''); ?>" name="user_post_title" id="user_post_title" class="inputwide" />
        Max 125 characters
        <div class="error" id="error_user_post_title"></div>
        <br />

        <input placeholder="Enter short description..." type="text" 
               value="<?PHP echo ((!empty($post_obj->post_excerpt))?$post_obj->post_excerpt:''); ?>" name="user_post_summary" id="user_post_summary" class="inputwide" />
        Max 250 characters
        <div class="error" id="error_user_post_summary"></div>
        <br />



        <?php 
        $cat_ids = array(90,91,92,93,94);
        $user_cats = array (
                'include' => implode(",", $cat_ids), //Only shows these 5 categories
                'hide_empty' => 0, 
                'show_option_none' =>'Choose category:',
                'sort_by'=>'name', 
        );
        $tag_str = NULL;
        if(!empty($post_obj)){
            $categories = wp_get_post_categories($post_obj->ID);
            $tags       = wp_get_post_tags($post_obj->ID,array('fields'=>'all'));
            if(count($categories)>0){
                foreach($categories as $cat) {
                    if(in_array($cat, $cat_ids)){
                        $user_cats['selected'] = $cat;
                    }
                }
            }
            if(count($tags)>0){

                foreach($tags as $tag) {
                    $tag_str[] = $tag->name;
                }
                $tag_str = implode(",", $tag_str);
            }
        }
        ?> <div class="styled-select"> <?php wp_dropdown_categories($user_cats); ?></div><?php
        ?>
        <div class="error" id="error_cat"></div>
        <br />
        <input type="hidden"  value="<?PHP echo $post_id; ?>"         
               name="post_id" id="post_id" />
        <input type="hidden" value="<?PHP echo $featured_img_id; ?>" 
               name="featured_img_id" id="featured_img_id" />


        <textarea name="user_post_content" id="user_post_content" placeholder="Enter your content..." class="inputwide"><?PHP echo ((!empty($post_obj->post_content))?$post_obj->post_content:''); ?></textarea>
        <div class="error" id="error_user_post_content"></div>
        (You can use basic html in this box. <a href="#">Click here for more info ADDLINK!!!</a>.)
        <br /><br />
        <label>Tags:</label> 
        <input placeholder="Seperated by commas" type="text" 
               value="<?PHP echo ((!is_null($tag_str)?$tag_str:'')); ?>" 
               name="user_post_tags" id="user_post_tags" /> (note: Only first 5 tags will be saved)
        <br /><br />

        <input class="cbutton" type="button" id="upload_img" value="Add/Switch Featured Image" />

            <div style="margin-top:10px;" id="featured_img_loading" class="loading">
                <img src="<?PHP bloginfo('template_directory'); ?>/images/ajaxloading-circul.gif" />
            </div>
            <div id="featured_img_ct" style="position:relative">
            <div style="margin-top:10px;" id="featured_img_div">
                <?PHP
                if($featured_img_id!=-1){
                    echo wp_get_attachment_image($featured_img_id, array(150,150));
                }
                ?>
            </div>
            <div id="featured_img_action" style="position:absolute;top:10px;left:100px;">
                <img src="<?PHP bloginfo('template_directory'); ?>/images/b_drop.png" id="remove_image_btn" style="cursor:pointer;" />
            </div>
            </div>

        <br /><br />




        <div class="loading" id="submit_loading">
            <img src="<?PHP bloginfo('template_directory'); ?>/images/ajaxloading_bar.gif" />
        </div>
        <div class="submit_div">
            <input class="cbutton" type="button"   name="submit_btn" id="user_post_submit"    value="<?PHP echo ((!empty($post_obj))?'Update':'Publish'); ?>">
            <input class="cbutton" type="button"   name="submit_btn" id="user_post_savedraft" value="Save Draft">
            <input class="cbutton" type="button"   name="submit_btn" id="user_post_preview"   value="Preview">
            <input class="cbutton" type="button" value="Discard" name="cancel" id="cancel_btn" />
        </div>

       <br /> 
    </form>





                </div><!-- #content -->
            </section><!-- #primary -->
    <?PHP
    if($featured_img_id!=-1){
        add_action('wp_footer','add_wp_footer');
    }
    function add_wp_footer(){
        ?>
    <script type="text/javascript">
        jQuery().ready(function(){
            jQuery('#featured_img_action').show();
        });
    </script>                
        <?PHP
    }
    ?>                
    <div id="dialog_message"></div> 
    <div style="display:none" id="for_preview">
        <a id="preview_link" target="_blank"></a>
    </div>
    <?php  get_sidebar('newpost'); ?>
    <?php  get_footer(); ?>
2
Eckstein

テンプレートフォルダのfunctions.phpにこれを追加してください。

<?php

//Set Default Meta Value
function set_default_meta_new_post($post_ID){
$current_field_value = get_post_meta($post_ID,'YOURMETAKEY',true); //change YOUMETAKEY to a default 
$default_meta = '100'; //set default value

if ($current_field_value == '' && !wp_is_post_revision($post_ID)){
    add_post_meta($post_ID,'YOURMETAKEY',$default_meta,true);
}
return $post_ID;
}

add_action('wp_insert_post','set_default_meta_new_post');

?>
4
jochem