假设我想在wordpress网站的主索引上显示某位作者的帖子,我该怎么做?以下是二十三个主题的循环:
<?php
$curauth = (isset($_GET['liamhodnett'])) ? get_user_by('liamhodnett', $author) : get_userdata(intval($author));
?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<li>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>">
<?php the_title(); ?></a>,
<?php the_time('d M Y'); ?> in <?php the_category('&');?>
</li>
<?php endwhile; else: ?>
<p><?php _e('No posts by this author.'); ?></p>
<?php endif; ?>
答案 0 :(得分:1)
<?php
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
?>
作者页面的示例:http://codex.wordpress.org/Author_Templates
<?php get_header(); ?>
<div id="content" class="narrowcolumn">
<!-- This sets the $curauth variable -->
<?php
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
?>
<h2>About: <?php echo $curauth->nickname; ?></h2>
<dl>
<dt>Website</dt>
<dd><a href="<?php echo $curauth->user_url; ?>"><?php echo $curauth->user_url; ?></a></dd>
<dt>Profile</dt>
<dd><?php echo $curauth->user_description; ?></dd>
</dl>
<h2>Posts by <?php echo $curauth->nickname; ?>:</h2>
<ul>
<!-- The Loop -->
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<li>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>">
<?php the_title(); ?></a>,
<?php the_time('d M Y'); ?> in <?php the_category('&');?>
</li>
<?php endwhile; else: ?>
<p><?php _e('No posts by this author.'); ?></p>
<?php endif; ?>
<!-- End Loop -->
</ul>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
修改强>
我将解释$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
做什么
isset($_GET['author_name']) ?
检查网址中是否存在带有用户名的参数,例如:www.myexamplewebsite.com/author/danieltulp
it is a shorthand if/else statement
如果网址具有用户名,则代码将尝试使用get_user_by('slug', $author_name)
如果没有,它将尝试使用get_userdata(intval($author))
3>的get_userdata Wordpress函数获取它
当然,你没有在URL中引用用户,所以你只需要设置currentauth,如:
$curauth = (is_home()) ? "liamhodnett" : (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
编辑2 如果所有其他方法都失败了(尚未测试上面的代码,那么很可能),请使用get_posts()进行自己的数据库调用:
$args = array(
'author' => 1 // this should be your user ID, or use 'author_name' => 'liamhodnett'
);
// get my posts 'ASC'
$myposts = get_posts( $args );
然后使用$ mypost数组进行循环:
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_content(); ?>
<?php endforeach;
wp_reset_postdata();?>