Search for the Article

Add CTA on Blog

To ensure that CTAs are inserted only after complete paragraphs or headings and that they appear correctly after reaching the specified word counts (100, 200, 300, 400), we need to adjust the logic. This updated code will check the total word count and only insert the CTA after a paragraph or heading has been fully processed. 

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 => '

Join Parimatch, Win Big.

', 200 => '

Download Parimatch, Win Daily.

', 300 => '

Live Streaming on Parimatch.

', 400 => '

Join Parimatch, Predict & Win.

', ]; // 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');