我使用以下代码在侧边栏中显示最喜欢的帖子的链接,但我想控制链接的数量,使其仅显示3个链接,如果超过这个数量,我希望显示查看所有收藏夹的链接。
PHP:
<?php
$favorites = va_get_dashboard_favorites($dashboard_user->ID, (bool) $is_own_dashboard );
if ( $favorites->post_count > 0 ) {
while ( $favorites->have_posts() ) : $favorites->the_post();
$post_status = $is_own_dashboard ? 'post-status' : '';
?>
<article id="post-<?php the_ID(); ?>" <?php post_class( $post_status ); ?>>
<a href="<?php echo get_permalink($ID); ?>">My link to a post or page</a><?php echo get_the_title($ID); ?>
</article>
<?php
endwhile;
} else {
?>
<?php
}
}
我怎样才能做到这一点?
请帮助
我在其他地方发现了va_get_dashboard_favorites函数,它看起来是一样的。最简单的方法是限制va_get_dashboard_favorites()WP_Query。例如
方法1
此代码是在wp-content/themes/vantage new/includs/dashboard.php中找到的:
function va_get_dashboard_favorites( $user_id, $self = false ) {
$favorites = new WP_Query( array(
'connected_type' => 'va_favorites',
'connected_items' => $user_id,
'nopaging' => true,
'posts_per_page' => 3, // limiting posts to 3
) );
return $favorites;
}
然后要添加view-all链接,只需在while循环中添加即可。例如
<?php
$favorites = va_get_dashboard_favorites($dashboard_user->ID, (bool) $is_own_dashboard );
if ( $favorites->post_count > 0 ) {
while ( $favorites->have_posts() ) : $favorites->the_post();
$post_status = $is_own_dashboard ? 'post-status' : '';
?>
<article id="post-<?php the_ID(); ?>" <?php post_class( $post_status ); ?>>
<?php get_template_part( 'content-listing', get_post_status() ); ?>
</article>
<?php
endwhile;
?>
<br /><a href="#yourview-all-link-here">View all</a>
<?php
} else {
?>
方法2(根据OP更新)
根据OP的评论,更新后的代码只显示3个链接
<?php
$favorites = va_get_dashboard_favorites($dashboard_user->ID, (bool) $is_own_dashboard );
$counter = 0;
$max = 3;
if ( $favorites->post_count > 0 ) {
while ( $favorites->have_posts() and ($counter < $max)) : $favorites->the_post();
$post_status = $is_own_dashboard ? 'post-status' : '';
?>
<article id="post-<?php the_ID(); ?>" <?php post_class( $post_status ); ?>>
<?php get_template_part( 'content-listing', get_post_status() ); ?>
</article>
<?php
$counter++;
endwhile;
?>
<br /><a href="#yourview-all-link-here">View all</a>
<?php
} else {
?>
我确信WP_Query在这种情况下会起作用。
<?php $posts = WP_Query(array(
'posts_per_page' => 3
//any other options can go in this array
)); ?>
// Your code goes here
<?php wp_reset_query(); ?> //This makes sure your query doesn't affect other areas of the page
<a href="linktomorefavorites/">View More</a>