美食博客开发求助:实现登录用户收藏食谱列表展示功能
嘿,我来帮你搞定这个收藏食谱展示的功能!根据你提到的已经创建了likes和recipes两个自定义文章类型,还有关联用的favorite_recipe_id字段,咱们一步步来实现这个功能:
1. 先限制仅登录用户可见
首先得确保这个收藏区域只对已登录用户展示,不然没意义。用WordPress内置的is_user_logged_in()函数判断就行:
<?php if (is_user_logged_in()) : ?> <div class="user-favorite-recipes"> <h3>我的心仪食谱</h3> <!-- 后续查询和展示代码放这里 --> </div> <?php endif; ?>
2. 查询当前用户的所有收藏记录
每个likes文章对应一条收藏记录,咱们要先把当前用户创建的所有有效likes条目查出来,同时确保favorite_recipe_id字段有值(避免无效记录):
<?php $current_user_id = get_current_user_id(); // 查询用户的所有likes条目 $liked_recipes_query = new WP_Query([ 'post_type' => 'likes', 'posts_per_page' => -1, // 显示全部收藏,也可以改成固定数量比如10 'post_status' => 'publish', 'author' => $current_user_id, 'meta_query' => [ [ 'key' => 'favorite_recipe_id', 'compare' => 'EXISTS' // 只保留有有效关联ID的记录 ] ] ]); ?>
3. 关联食谱并批量查询展示
为了避免多次单独查询食谱(影响性能),咱们先把所有收藏的食谱ID收集起来,再批量查询对应的recipes文章:
<?php if ($liked_recipes_query->have_posts()) : ?> <?php // 收集所有关联的食谱ID $recipe_ids = []; while ($liked_recipes_query->have_posts()) { $liked_recipes_query->the_post(); $recipe_id = get_post_meta(get_the_ID(), 'favorite_recipe_id', true); if (!empty($recipe_id) && is_numeric($recipe_id)) { $recipe_ids[] = $recipe_id; } } wp_reset_postdata(); // 重置查询上下文,避免影响其他内容 // 批量查询对应的食谱 $favorite_recipes_query = new WP_Query([ 'post_type' => 'recipes', 'posts_per_page' => -1, 'post_status' => 'publish', 'post__in' => $recipe_ids, 'orderby' => 'post__in' // 保持用户收藏的顺序 ]); ?> <?php if ($favorite_recipes_query->have_posts()) : ?> <ul class="favorite-recipes-list"> <?php while ($favorite_recipes_query->have_posts()) : $favorite_recipes_query->the_post(); ?> <li class="favorite-recipe-item"> <a href="<?php the_permalink(); ?>"> <?php if (has_post_thumbnail()) : ?> <?php the_post_thumbnail('medium'); ?> <?php endif; ?> <h4><?php the_title(); ?></h4> <p><?php echo wp_trim_words(get_the_content(), 20); ?></p> </a> <!-- 这里可以加取消收藏的按钮,后续可以实现删除对应的likes文章 --> </li> <?php endwhile; ?> </ul> <?php wp_reset_postdata(); ?> <?php else : ?> <p>暂时还没有收藏任何食谱哦,快去探索美味吧!</p> <?php endif; ?> <?php else : ?> <p>暂时还没有收藏任何食谱哦,快去探索美味吧!</p> <?php endif; ?>
几个实用的优化建议
- 避免重复收藏:在食谱详情页的收藏按钮逻辑里,先检查当前用户是否已经存在对应
favorite_recipe_id的likes文章,防止重复创建。 - 添加取消收藏功能:可以在每个收藏食谱条目里加个按钮,点击后通过AJAX删除对应的
likes文章,提升用户体验。 - 性能优化:如果用户收藏量很大,不要用
posts_per_page => -1,改成分页展示或者限制显示前10条,再做个“查看更多”按钮。 - 样式美化:给
.user-favorite-recipes、.favorite-recipes-list这些类写点CSS,让收藏列表看起来更精致,比如卡片式布局、图片圆角等。
内容的提问来源于stack exchange,提问作者Ale
相关产品推荐
相关产品推荐

