Convert a custom query to a function and get a shortcode
Question
I am a newbie with PHP and WP. This works but I would like to convert it into a function to call it as a shortcode in the middle of a post.
How to “convert” this one?
Thanks
<?php // related posts based on first tag of current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$first_tag = $tags[0]->term_id;
$args = array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts' => 1, // how many posts?
'caller_get_posts' => 1
);
$my_query = new WP_Query($args);
if ($my_query->have_posts()) { ?>
<div class="cornice-plus">
`<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>`
<div class="post-plus">
<a href="<?php the_permalink() ?>">
<?php if ( wp_is_mobile() )
the_post_thumbnail('medium');
else
the_post_thumbnail('', array('title' => ''.get_the_title().'' )); ?>
</a>
<div class="right">
<h5>
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php printf(__('%s', 'max-magazine'), the_title_attribute('echo=0')); ?>">
<?php
// display only first 22 characters in the title.
$short_title = substr(the_title('','',FALSE),0,156);
echo $short_title;
if (strlen($short_title) > 155){
echo '...';
}
?>
</h5>
<div class="description">
<?php
//display only first 150 characters in the slide description.
$excerpt = get_the_excerpt();
echo substr($excerpt,0, 150);
if (strlen($excerpt) > 149){
echo '...';
}
?>
</div> </a>
</div>
</div>
<!--<li><a href="<?php //the_permalink(); ?>"><?php //the_title(); ?></a></li>-->
</div>
<?php endwhile; ?>
<?php } ?>
<?php } ?>
0
functions, shortcode, wp-query
3 years
2020-04-05T20:51:02-05:00
2020-04-05T20:51:02-05:00 0 Answers
95 views
0
Leave an answer