orlafitz
orlafitz

Reputation: 101

Positioning of get_template_part()

I created a shortcode to display social icons within the theme I am using (Divi). The social icons are contained in a PHP template called "social_icons.php".

This is the function I am using:

  function social_icons_shortcode() {
    $social_icons = get_template_part( 'includes/social_icons' );
      echo $social_icons; 
}
add_shortcode('social-icons', 'social_icons_shortcode');

Here is the the social_icons.php template:

<div id="custom-social-icons">
    <?php if( get_field('facebook', 'option') ): ?>
        <a class="icon facebook" href="<?php echo get_field( 'facebook', 'option' ) ?>" title="Follow us on Facebook"></a>
    <?php endif; ?>
    <?php if( get_field('twitter', 'option') ): ?>
    <a class="icon twitter" href="<?php echo get_field( 'twitter', 'option' ) ?>" title="Follow us on Twitter"></a>
    <?php endif; ?>
    <?php if( get_field('instagram', 'option') ): ?>
    <a class="icon instagram" href="<?php echo get_field( 'instagram', 'option' ) ?>" title="Follow us on Instagram"></a>
    <?php endif; ?>
    <?php if( get_field('youtube', 'option') ): ?>
    <a class="icon youtube" href="<?php echo get_field( 'youtube', 'option' ) ?>" title="Follow us on YouTube"></a>
    <?php endif; ?>
    <?php if( get_field('linkedin', 'option') ): ?>
    <a class="icon linkedin" href="<?php echo get_field( 'linkedin', 'option' ) ?>" title="Find us on Linkedin"></a>
    <?php endif; ?>
</div>

The shortcode works fine when I want to show the social icons in the footer of the theme but when I try to put them into the body (eg: the contact page) they are displaying absolute at the upper left hand corner of the page. See Screenshot: https://share.getcloudapp.com/8LuJkODx

I cannot figure out why this is happening - is there something I am doing wrong with get_template_part()?

Upvotes: 0

Views: 243

Answers (1)

disinfor
disinfor

Reputation: 11533

Ahh..I see what the problem is. You need to return the value, not echo.

function social_icons_shortcode() {
    $social_icons = get_template_part( 'includes/social_icons' );
    return $social_icons; 
}
add_shortcode('social-icons', 'social_icons_shortcode');

The other thing that may happen because how get_template_part() works, you may need to use an ob_buffer.

function social_icons_shortcode() {
      ob_start();
      get_template_part( 'includes/social_icons' );
      return ob_get_clean(); 
}
add_shortcode('social-icons', 'social_icons_shortcode');

Upvotes: 2

Related Questions