Question

I am beginner in wordpress and i would like to ask some help. I need some hook , which will split the post after some number of characters (lets say 300) and will add my text after each split.I created filter hook, but i do not know how to create action hook - to write splitted text with my text to database before save,publish or edit action. This code works , but how to save to database?

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');
Was it helpful?

Solution

You are looking for wp_insert_post_data filter. In this function, to parameter is supplied for you to filter the data before it is inserted. You can use it like -

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top