• I’m using this code to show related post based from tag, i add it in the template page and works good, but there is a way to add it in functions.php page theme ?

    <?php
    $tags = wp_get_post_tags($post->ID);
    if ($tags) {
    	$tag_ids = array();
    	foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
    
    	$args=array(
    		'tag__in' => $tag_ids,
    		'post__not_in' => array($post->ID),
    		'showposts'=>5, // Number of related posts that will be shown.
    		'caller_get_posts'=>1
    	);
    	$my_query = new wp_query($args);
    	if( $my_query->have_posts() ) {
    		echo '<h3>Related Posts</h3><ul>';
    		while ($my_query->have_posts()) {
    			$my_query->the_post();
    		?>
    			<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
    		<?php
    		}
    		echo '</ul>';
    	}
    }
    ?>
Viewing 3 replies - 1 through 3 (of 3 total)
  • Here is a good tutorial on how to make your own functions:

    http://www.pearsonified.com/2008/05/how-to-use-wordpress-functions.php

    What about:

    function my_function($tags) {
    	if ($tags) {
    		$tag_ids = array();
    		foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
    
    		$args=array(
    			'tag__in' => $tag_ids,
    			'post__not_in' => array($post->ID),
    			'showposts'=>5, // Number of related posts that will be shown.
    			'caller_get_posts'=>1
    		);
    		$my_query = new wp_query($args);
    		if( $my_query->have_posts() ) {
    			echo '<h3>Related Posts</h3><ul>';
    			while ($my_query->have_posts()) {
    				$my_query->the_post();
    			?>
    				<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
    			<?php
    			}
    			echo '</ul>';
    		}
    	}
    }

    then call it with <?php my_function(wp_get_post_tags($post->ID));?>

    Thread Starter Marcomail

    (@marcomail)

    Thanks, but why if i use this code when i put a comment it appear under the last related posts published and not in the correct page ?

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘How can i add this code on functions.php ?’ is closed to new replies.