标签: 按分类ID

  • wordpress按分类ID调用最新、推荐、随机内容

    在WordPress中,可以通过自定义查询(WP_Query)来按分类ID调用最新、推荐(自定义字段或标签)、随机内容。以下是一些示例代码,帮助你实现这些功能。

    1. 按分类ID调用最新内容

    以下代码可以调用指定分类ID下的最新文章:

    <?php
    // 设置分类ID和文章数量
    $category_id = 1; // 替换为你的分类ID
    $posts_per_page = 5; // 显示的文章数量
    
    $args = array(
        'post_type' => 'post', // 文章类型
        'posts_per_page' => $posts_per_page, // 每页显示的文章数量
        'orderby' => 'date', // 按日期排序
        'order' => 'DESC', // 降序排列(最新文章在前)
        'cat' => $category_id // 指定分类ID
    );
    
    $query = new WP_Query($args);
    
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            ?>
            <div class="post-item">
                <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                <p><?php the_excerpt(); ?></p>
            </div>
            <?php
        }
    } else {
        echo '<p>没有找到文章。</p>';
    }
    
    wp_reset_postdata(); // 重置查询
    ?>

    2. 按分类ID调用推荐内容

    推荐内容可以通过自定义字段或标签实现。假设你使用自定义字段is_recommended来标记推荐文章(值为true或1):

    <?php
    $category_id = 1; // 替换为你的分类ID
    $posts_per_page = 5; // 显示的文章数量
    
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $posts_per_page,
        'orderby' => 'date', // 按日期排序
        'order' => 'DESC', // 降序排列
        'cat' => $category_id,
        'meta_query' => array( // 自定义字段查询
            array(
                'key' => 'is_recommended', // 自定义字段名称
                'value' => 'true', // 自定义字段值
                'compare' => '='
            )
        )
    );
    
    $query = new WP_Query($args);
    
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            ?>
            <div class="post-item">
                <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                <p><?php the_excerpt(); ?></p>
            </div>
            <?php
        }
    } else {
        echo '<p>没有找到推荐文章。</p>';
    }
    
    wp_reset_postdata(); // 重置查询
    ?>

    调用随机内容

    以下代码可以调用指定分类ID下的随机文章:

    <?php
    $category_id = 1; // 替换为你的分类ID
    $posts_per_page = 5; // 显示的文章数量
    
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $posts_per_page,
        'orderby' => 'rand', // 随机排序
        'cat' => $category_id
    );
    
    $query = new WP_Query($args);
    
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            ?>
            <div class="post-item">
                <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                <p><?php the_excerpt(); ?></p>
            </div>
            <?php
        }
    } else {
        echo '<p>没有找到文章。</p>';
    }
    
    wp_reset_postdata(); // 重置查询
    ?>