Updated Code
Replace your existing function in functions.php with the following code:
function insert_dynamic_cta($content) {
// Split the content into paragraphs to maintain structure
$paragraphs = explode("\n", $content);
$new_content = '';
$current_word_count = 0;
// Initialize an array for CTAs with hyperlinks
$ctas = [
100 => '',
200 => '',
300 => '',
400 => '',
];
// Loop through each paragraph
foreach ($paragraphs as $paragraph) {
// Count words in the current paragraph
$word_count_in_paragraph = str_word_count($paragraph);
$current_word_count += $word_count_in_paragraph;
// Add the paragraph to the new content
$new_content .= $paragraph . "\n";
// Check for CTAs at the specified word counts
foreach ($ctas as $count => $cta) {
if ($current_word_count >= $count) {
$new_content .= $cta; // Insert the CTA
unset($ctas[$count]); // Remove the CTA once added
}
}
}
// Trim any extra whitespace and return the modified content
return trim($new_content);
}
add_filter('the_content', 'insert_dynamic_cta');