如何为特定CPT的帖子设置内容?

时间:2016-03-19 作者:ShoeLace1291

我有一个叫竞赛的CPT。创建或更新竞赛时,我想从插件中手动将帖子内容的值设置为我的快捷码。我有与此CPT一起使用的自定义元框,因此帖子的内容将基于这些元框的值。我试过了add_filter(\'the_content\', \'my_content\') 但不会对数据库中的post\\u content列进行任何更改。我做错了什么?

注:我使用wp_die() 查看是否调用了筛选器,以及wp_die() 什么都没做。

这是我的代码:

function imgw_meta_boxes(){
    add_meta_box( \'contest-dates\', __(\'Running Dates\'), \'imgw_dates_metabox\', \'contest\' );
    add_meta_box( \'contest-description\', __(\'Description/Rules\'), \'imgw_description_editor\', \'contest\' );
}
add_action( \'add_meta_boxes\', \'imgw_meta_boxes\' );

function imgw_dates_metabox($object){

      wp_nonce_field(basename(__FILE__), "meta-box-nonce");
?>
<div>
<label>Starting Date</label>
<input type="date" name="contest-starting-date" value="<?php echo get_post_meta($object->ID, "contest-starting-date", true); ?>"> at <input type="time" name="contest-starting-time" value="<?php echo get_post_meta($object->ID, "contest-starting-time", true); ?>">
<label>Ending Date</label>
<input type="date" name="contest-ending-date" value="<?php echo get_post_meta($object->ID, "contest-ending-date", true); ?>"> at <input type="time" name="contest-ending-time" value="<?php echo get_post_meta($object->ID, "contest-ending-time", true); ?>">
</div>

<?php
} 

function imgw_description_editor($object){ ?>
<textarea name="contest-description" rows="10" cols="100" placeholder="Enter a description or rules..."><?php echo get_post_meta($object->ID, \'contest-description\', true); ?></textarea>
<?php    
}
function imgw_save_contest_meta( $post_id, $post ) {

    global $post;

  if($post->post_type == \'contest\')
    return;

    update_post_meta( $post_id, \'contest-description\', $_POST[\'contest-description\'] );
    update_post_meta( $post_id, \'contest-starting-date\', $_POST[\'contest-starting-date\'] );
    update_post_meta( $post_id, \'contest-starting-time\', $_POST[\'contest-starting-time\'] );
    update_post_meta( $post_id, \'contest-ending-date\', $_POST[\'contest-ending-date\'] );
    update_post_meta( $post_id, \'contest-ending-time\', $_POST[\'contest-ending-time\'] );

} // end save_meta_data

add_action(\'save_post\', \'imgw_save_contest_meta\', 10, 3);

function imgw_contest_content( $content ){

    global $post;

    if($post->post_type == \'contest\'){
        $content = "[imgw-contest][/imgw-contest]";
        return $content;  

    }      

    wp_die(\'Hello!\');

}

add_filter(\'the_content\', \'imgw_contest_content\');

1 个回复
SO网友:jgraup

要更新数据库中帖子的属性,请使用wp_update_post.

// Update post 37
  $my_post = array(
      \'ID\'           => 37,
      \'post_title\'   => \'This is the post title.\',
      \'post_content\' => \'This is the updated content.\',
  );

// Update the post into the database
  wp_update_post( $my_post );
只是要小心infinite loop 更新帖子时。

相关推荐