WordPress custom fields - Function
I'd love any ideas.
This is what i have inside the loop
<?php
$mediapost = get_post_meta($post->ID, 'mediapost', true);
if ($mediapost == 'gallery') {
$posticon = '<i class="fa fa-camera-retro"></i> ';
} elseif ($mediapost == 'video') {
$posticon = '<i class="fa fa-video-camera"></i> ';
} else {
$posticon = '';
}
?>
<?php echo $posticon; ?> <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php printf( esc_attr__( 'Permalink to %s', 'citydesk' ), the_title_attribute( 'echo=0' ) ); ?>" ><?php the_title(); ?></a>
I have around 5 loops and same code keeps repeating one after another.
Is there a way to shorten this (maybe to wrap it in a function) and use it that way?
Solutions
You should consider using wordpress post formats:
It implements this interface in posts admin area :
Also a few functions to know what kind of post is it:
has_post_format( '[type]' )
So you can create a function in you
function.php
file:
function the_post_icon(){
$format = get_post_format();
switch($format){
case 'gallery':
$posticon = 'gallery';
break;
case 'video':
$posticon = 'video';
break;
default:
$posticon = '';
break;
}
echo '<i class="fa fa-'.$posticon.'"></i> ';
}
or even
function the_post_icon(){
echo '<i class="fa fa-'.get_post_format().'"></i> ';
}
You could use a
switch
though with only the three options it doesn't save you any code:
switch(type){
case 'gallery':
$posticon = '<i class="fa fa-camera-retro"></i> ';
break;
case 'video':
$posticon = '<i class="fa fa-video-camera"></i> ';
break;
default:
$posticon = '';
break;
}