Add function after the_content

The main issue in your code is caused by the call to zss_social_buttons() in your filter function:

// In zss_insert_share_buttons():

$social_share_buttons = zss_social_buttons(); // NULL
$content .= $social_share_buttons;

And the problem there is that zss_social_buttons() is echoing the sharing links/buttons instead of returning them, so they’re not actually added to the $content variable. Instead, they’re sent to the browser (or displayed) immediately when the function runs.

So that explains why the buttons appear before the post content. ( That’s what you meant by “the zss_social_buttons() function loads before the_content();“, right? )

Additionally, the Facebook script and including the <div id="fb-root"></div> should be added only once and not every time the filter the_content is applied. So for example, you can use the wp_body_open (action) hook to add the script right after the <body> tag:

add_action( 'wp_body_open', 'my_wp_body_open' );
function my_wp_body_open() {
    ?>
        <!-- Load Facebook SDK for JavaScript -->
        <div id="fb-root"></div>
        <script>put the script code here</script>
    <?php
}

And then, to fix the main issue, you can either:

  • Make the zss_social_buttons() function returns the output and not echoing it. Simplified example:

    <?php
    function zss_social_buttons() {
        return '<div class="zss">
            <!-- Facebook -->
            <div class="fb-share-button" data-href="' . esc_url( get_the_permalink() ) . '"' .
                ' data-layout="button_count" data-lazy="true"></div>
    
            ... your other buttons.
        </div>';
    }
    
  • Or you can use output buffering in the zss_insert_share_buttons() function:

    <?php
    function zss_social_buttons() {
        ?>
            <div class="zss">
                <!-- Facebook -->
                <div class="fb-share-button" data-href="<?php the_permalink(); ?>"
                    data-layout="button_count" data-lazy="true"></div>
    
                ... your other buttons.
            </div>
        <?php
    }
    
    function zss_insert_share_buttons( $content ) {
        if ( is_singular() && in_the_loop() && is_main_query() ) {
            ob_start();
    
            zss_social_buttons(); // echo the output, but send it to the buffer and
                                  // not the browser
    
            $content .= ob_get_clean(); // and then append the buffer to $content
        }
    
        return $content;
    }
    

tech