• WordPress无插件相关日志修改版

    同样的,此文也是对网友做过的东西修改了下,这个修改版的优点在于,如果相关日志找不到,那么就输出随机日志

    原版php代码从老万那粘过来(地址:WordPress 非插件相关日志的两种方法 中的方法二)

    <h3>相关日志</h3>
    <ul>
    	<?php
    	$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'=>10,
    			'caller_get_posts'=>1
    			);
    		$my_query = new WP_Query($args);
    		if( $my_query->have_posts() ) {
    			while ($my_query->have_posts()) : $my_query->the_post(); ?>
    			<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
    				<?php the_title();?>
    				<?php comments_number(' ','(1)','(%)'); ?>
    				</a>
    			</li>
    			<?php endwhile;
    			}
    	}
    	wp_reset_query();
    	?>
    </ul>
    

    我的修改版php代码(放在single.php中合适位置)

    <ul id="randomposts">
    	<?php
    		$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'=>10,
    				'caller_get_posts'=>1
    			);
    			$my_query = new WP_Query($args);
    			if( $my_query->have_posts() ) {
    				echo '<h3>相关日志</h3>';
    				while ($my_query->have_posts()) : $my_query->the_post(); ?>
    					<li><?php the_time('Y年m月d日') ?>
    					-- <a href="<?php the_permalink() ?>" rel="bookmark" title="查看>>
    					<?php the_title_attribute(); ?>">
    					<?php the_title(); ?>
    					<?php comments_number(' ','(1)','(%)'); ?>
    					</a> </li>
    			<?php
    				endwhile;
    			}else{
    				echo '<h3>随机日志</h3>';
    				$posts = get_posts('numberposts=10&orderby=rand');
    				foreach($posts as $post) {
    				setup_postdata($post);
    				echo '<li>';
    				the_time('Y年m月d日');
    				echo ' -- <a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
    			}
    			$post = $posts[0];
    			}
    			wp_reset_query();
    		}
    	?>
    </ul>
    
    

    CSS代码

    #randomposts h3{color:#F60;margin-left:5px;padding:5px 0}
    #randomposts li{list-style:circle;margin:0 0 7px 40px;font-size:12px}