Wordpress钩子在发布保存之前写入数据库

时间:2013-12-21 08:57:31

标签: wordpress split character publish before-save

我是wordpress的初学者,我想请一些帮助。 我需要一些钩子,它会在一些字符之后拆分帖子(比方说300)并在每次拆分后添加我的文本。我创建了过滤器钩子,但我不知道如何创建动作钩子 - 用分割文本写入保存,发布或编辑操作之前,我的文本到数据库。这段代码有效,但如何保存到数据库?

function inject_ad_text_after_n_chars($content) {

  $enable_length = 30;
  global $_POST;
  if (is_single() && strlen($content) > $enable_length) {

$before_content = substr($content, 0, 30);
$before_content2 = substr($content, 30, 30);
$before_content3 = substr($content, 60, 30);
$before_content4 = substr($content, 90, 30);
$texta = '00000000000000000000';  

                 return $before_content . $texta . $before_content2 . $texta . $before_content3 . $texta . $before_content4;

}
  else {
    return $content;
  }
}

add_filter('the_content', 'inject_ad_text_after_n_chars');

1 个答案:

答案 0 :(得分:3)

您正在寻找wp_insert_post_data过滤器。在此函数中,为您提供了参数,以便在插入数据之前对其进行过滤。您可以像 -

一样使用它
add_filter('wp_insert_post_data', 'mycustom_data_filter', 10, 2);
function mycustom_data_filter($filtered_data, $raw_data){
    // do something with the data, ex

    // For multiple occurence
    $chunks = str_split($filtered_data['post_content'], 300);
    $new_content = join('BREAK HERE', $chunks);

    // For single occurence
    $first_content = substr($filtered_data['post_content'], 0, 300);
    $rest_content = substr($filtered_data['post_content'], 300);
    $new_content = $first_content . 'BREAK HERE' . $rest_content;

    // put into the data
    $filtered_data['post_content'] = $new_content;

    return $filtered_data;
}