I want to display a contact-widget in my custom Wordpress theme, so I placed it in a shortcode so I can call it any time and any place. The problem is that the shortcode shows on top of the original I placed the shortcode in. This happens with widgets, normal text-fields etc.
First I added the line
add_filter( 'widget_text', 'do_shortcode' );
to enable the fields for showing shortcodes.
In my functions.php I placed the following code where I call a template part with the contact information. I saw another topic where they solved the problem by return
'ing a variable.
// contact widget
function contact_info_shortcode() {
$contact = get_template_part('includes/sections/contact', 'info');
return $contact;
}
add_shortcode('contact_info', 'contact_info_shortcode');
In that code I call the following template file that shows my contact information
<?php
$contact_title = get_field('contact-titel', 'option');
$phone = get_field('telefoon', 'option');
$email = get_field('e-mail', 'option');
$adress = get_field('adres', 'option');
$place = get_field('plaats', 'option');
;?>
<table class="contact-table">
<!-- telefoon -->
<tr>
<td><i class="fas fa-phone"></i></td>
<td><a class="contact-info-link" href="<?php echo $phone['url'];?>" target="<?php echo $phone['target'];?>"><?php echo $phone['title'];?></a></td>
</tr>
<!-- email -->
<tr>
<td><i class="fas fa-envelope"></i></td>
<td><a class="contact-info-link" href="<?php echo $email['url'];?>" target="<?php echo $email['target'];?>"><?php echo $email['title'];?></a></td>
</tr>
<!-- adres -->
<tr>
<td><i class="fas fa-map-marker-alt"></i></td>
<td>
<p class="contact-info-adress"><?php echo $adress;?></p>
<p class="contact-info-adress"><?php echo $place;?></p>
</td>
</tr>
</table>
Hope you guys know what I'm doing wrong
This is because get_template_part()
is really just a wrapper for an include, which is essentially echoing
the template part, so you can't assign it to a variable.
What you need to do is hold the template part in an output buffer
and then return the output buffer.
function contact_info_shortcode() {
// Here we start the output buffer.
ob_start();
// This is now held in the output buffer.
get_template_part('includes/sections/contact', 'info');
// Now we can return the data in the output buffer.
return ob_get_clean();
}
add_shortcode('contact_info', 'contact_info_shortcode');