WordPress 展示随机帖子
function wpb_rand_posts() { 
    $string = ''; // 初始化字符串变量

    $args = array(
        'post_type' => 'post',
        'orderby'   => 'rand',
        'posts_per_page' => 5,
    );

    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) {
        $string .= '<ul>';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $string .= '<li><a href="'. get_permalink() .'">'. get_the_title() .'</a></li>';
        }
        $string .= '</ul>';
        /* 恢复原始文章数据 */
        wp_reset_postdata();
    } else {
        $string .= 'no posts found';
    }

    return $string;
}

add_shortcode('wpb-random-posts', 'wpb_rand_posts');
add_filter('widget_text', 'do_shortcode');

代码解析:

  1. wpb_rand_posts 函数:
  • 使用 WP_Query 查询 5 篇随机的文章(通过 'orderby' => 'rand' 实现)。

  • 如果找到了文章,使用 while 循环生成一个无序列表 (<ul>),每篇文章的标题都链接到它的详细页面 (<a> 标签)。

  • 如果没有找到文章,则显示 'no posts found'

    1. add_shortcode 函数:
  • wpb_rand_posts 函数注册为一个 WordPress 短代码 [wpb-random-posts],你可以在页面或文章中插入这个短代码来显示随机文章。

    1. add_filter 函数:
  • 确保短代码可以在小工具文本区域中使用(通过 do_shortcode)。

[wpb-random-posts]
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇