php - How can I make a reusable WordPress function? -
i have routine generates list of related posts, intended use in single.php:
//for use in loop, list 5 post titles related first tag on current post $tags = wp_get_post_tags($post->id); if ($tags) { echo 'related posts'; $first_tag = $tags[0]->term_id; $args=array( 'tag__in' => array($first_tag), 'post__not_in' => array($post->id), 'showposts'=>5, 'caller_get_posts'=>1 ); $my_query = new wp_query($args); if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?> <a href="<?php the_permalink() ?>" rel="bookmark" title="permanent link <?php the_title_attribute(); ?>"><?php the_title(); ?></a> <?php endwhile; } wp_reset_query(); } what need add function.php can call function in wordpress post editor?
as $post variable global in wp, can following:
function dostuff() { global $post; $tags = wp_get_post_tags($post->id); if ($tags) { echo 'related posts'; $first_tag = $tags[0]->term_id; $args=array( 'tag__in' => array($first_tag), 'post__not_in' => array($post->id), 'showposts'=>5, 'caller_get_posts'=>1 ); $my_query = new wp_query($args); if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?> <a href="<?php the_permalink() ?>" rel="bookmark" title="permanent link <?php the_title_attribute(); ?>"><?php the_title(); ?></a> <?php endwhile; } wp_reset_query(); } } now can put <?php dostuff() ?> in template.
note however, functions using $post must used within “the loop”.
Comments
Post a Comment