Ask for Comments at 50% of paragraphs

With this very easy snippet, to all posts a container will be inserted at 50% of the posts paragraphs that asks for feedback/comments. In this version, it’s german and the currently used version on gooloo.de. You can alter it to your personal needs. The text is responsive, creating a one-line headline on all screen sizes and smaller text below it.

Add it to your Code Snippets Plugin, or your theme’s functions.php and alter the text to your needs.

// Function to modify the content
function add_comment_prompt_content($content) {
    global $post;
    
    $prompt_html = '
    <hr style="width: 100%; margin: 2em 0;">
    <div style="text-align: center; padding: 2em 0;">
        <h2 style="font-size: clamp(2rem, 6vw, 3.5rem); font-weight: 700; margin-bottom: 1em;">
            Dein Kommentar zählt
        </h2>
        <p style="font-size: 1.1rem; line-height: 1.5; max-width: 800px; margin: 0 auto;">
            Bitte nimm dir einen Moment Zeit, anderen von deinen Erfahrungen zu berichten, indem Du unten einen Kommentar hinterlässt. Danke.
        </p>
    </div>
    <hr style="width: 100%; margin: 2em 0;">
    ';

    // Split content into paragraphs
    $parts = preg_split('/(<\/p>)/', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
    $total_parts = count($parts);
    $middle = floor($total_parts / 2);
    
    // Insert prompt at middle point
    array_splice($parts, $middle, 0, $prompt_html);
    
    return implode('', $parts);
}

// Add the filter when the main loop starts
add_action('loop_start', function($query) {
    if ($query->is_main_query() && is_single()) {
        add_filter('the_content', 'add_comment_prompt_content', 20);
    }
});

// Remove the filter when main loop ends
add_action('loop_end', function($query) {
    if (has_filter('the_content', 'add_comment_prompt_content')) {
        remove_filter('the_content', 'add_comment_prompt_content');
    }
});

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *