主页/WordPress笔记/博客文章/综合文章/如何从WordPress文章循环中排除最新文章

如何从WordPress文章循环中排除最新文章

Bug编译狮

Bug编译狮

要从WordPress文章循环中排除最新文章,你可以使用以下方法:

  1. 使用posts_where过滤器: 通过修改posts_where过滤器来排除最新的文章。

  2. 创建自定义插件或主题函数: 使用PHP编写函数,动态地生成文章列表。

  3. 使用WP_Querymeta_query参数: 如果你需要更复杂的逻辑,可以使用meta_query参数。

下面是示例代码和详细步骤:

示例代码

// 创建自定义函数,用于排除最新文章
function exclude_latest_posts($query) {
    if ($query->is_home() && $query->is_main_query()) { // 检查是否为首页并为主查询
        $args = array(
            'post__not_in' => get_option('recent_posts'), // 获取最新文章ID数组
        );
        $query->set('post__in', $query->get('post__in') - array_keys($args['post__not_in'])); // 移除最新文章ID
    }
}
add_filter('pre_get_posts', 'exclude_latest_posts');

步骤说明

  1. 创建自定义函数:上述代码定义了一个名为exclude_latest_posts的自定义函数。
  2. 检查条件:该函数首先检查当前页面是否为首页($query->is_home())并且是否为主查询($query->is_main_query())。
  3. 获取最新文章ID:使用get_option('recent_posts')获取最新文章ID数组。
  4. 移除最新文章ID:通过调用$query->set('post__in', ...)设置新的文章ID数组,从而移除最新文章。

效果

当这个函数被添加到WordPress的钩子后,每次当你访问首页时,它都会自动排除最新文章,确保首页显示的是其他文章而不是最新的那篇。

注意事项

  • 这个方法适用于静态页面(如博客首页),如果需要动态更新,可能需要结合WP_Querymeta_query参数来实现更复杂的需求。
  • 确保在安全的前提下使用此代码,避免潜在的安全风险。

希望这能帮助你解决从WordPress文章循环中排除最新文章的问题!如果你有任何进一步的问题,请随时提问。

黑板前的Bug语法讲师

黑板前的Bug语法讲师

教案大纲

  1. 引入
  2. 定义问题:找出并排除WordPress文章列表中的“最新”文章。
  3. 解决方案
    1. 使用WP_Query过滤器(适用于WordPress 5.0+)
    2. 自定义函数(适用于WordPress 4.9-5.0)
  4. 示例代码
    • 自定义函数示例(WordPress 4.9-5.0)
    • WP_Query 示例(WordPress 5.0+)

1. 引入

首先了解一下WordPress的文章结构和查询方法。

<?php
/**
 * WordPress function to get the latest posts.
 *
 * @param int $post_type The post type to query for.
 */
function wp_get_latest_posts($post_type = 'all') {
    global $wpdb;

    // Get all posts by default.
    $query_args = [
        'posts_per_page' => -1,
        'order'          => 'DESC',
        'orderby'        => 'ID',
        'meta_key'       => '_wp_attachment_metadata',
        'post__not_in'   => array(1, 2),
        'post_type'      => $post_type,
        'post_status'    => 'publish'
    ];

    // Apply filters to the query arguments.
    apply_filters('wp_get_latest_posts_query_args', $query_args);

    // Query and return the results.
    $latest_posts = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT *
              FROM $wpdb->posts
             WHERE $wpdb->posts.post_type = %s
               AND $wpdb->posts.post_status = 'publish'
               ORDER BY $wpdb->posts.date_posted DESC",
            $post_type
        ),
        ARRAY_A
    );

    return $latest_posts;
}

2. 定义问题

我们需要从WordPress文章列表中排除最新文章,这可以通过修改WP_Query过滤器来实现。

$latest_posts = wp_get_latest_posts();
// 假设我们想要获取所有的文章,这里只是提供一个例子
$all_posts = wp_get_posts(array(
    'numberposts' => -1,
    'post_type' => 'all',
));

foreach ($all_posts as $post) {
    foreach ($latest_posts as $latest) {
        if ($latest['ID'] === $post['ID']) {
            unset($all_posts[$i]);
            break;
        }
    }
}

echo '<pre>';
print_r($all_posts);
echo '</pre>';

3. 解决方案

  • 使用WP_Query过滤器结合自定义函数或宏,根据需要选择合适的处理方式。
  • 可以通过以下几种方式解决:

    • 使用WP_Query过滤器

      $query_args = ['post_type' => 'your-post-type', 'orderby' => 'date', 'order' => 'desc'];
      $latest_posts = new WP_Query($query_args);
      while ($latest_posts->have_posts()) : $latest_posts->the_post(); ?>
      <div><?php the_title(); ?></div>
      <?php endwhile; ?>
    • 自定义函数

      
      function exclude_latest_posts() {
      global $wpdb;
      
      $query_args = [
      'post_type' => 'your-post-type',
      'orderby' => 'date',
      'order' => 'desc',
      ];
      
      $query = new WP_Query($query_args);
      
      while ($query->have_posts()) {
      $query->the_post();
      
      if (is_single()) {
        $latest_id = get_the_ID();
      
        if (!empty($latest_id)) {
          $exclude_ids[] = $latest_id;
        }
      }
      }
      
      return $exclude_ids;
      }

    add_filter(‘wp_get_recent_posts’, ‘exclude_latest_posts’);

4. 示例代码

示例代码

自定义函数示例(WordPress 4.9-5.0)

function exclude_last_posts($args) {
    global $wpdb;

    // 获取当前时间戳
    $now = time();

    // 防止在禁用时出现错误
    if (!$wpdb->allow_no_rewrite) {
        return $args;
    }

    $query_args = [];
    $query_args['post_type'] = $args['post_type'];
    $query_args['post_status'] = 'publish';
    $query_args['meta_key'] = '_wp_attachment_metadata';
    $query_args['meta_value'] = $now;
    $query_args['orderby'] = 'date';

    // 检查是否有指定的标签
    $exclude_tag = isset($_GET['exclude_tag']) ? $_GET['exclude_tag'] : '';
    if (!empty($exclude_tag)) {
        $query_args['post_tags'] = array_unique(array_merge(get_terms('post_tag'), explode(',', $exclude_tag)));
    }

    // 进行筛选
    $query = new WP_Query($query_args);

    // 如果有结果,则显示
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();

            // 在单个页面中删除最后一个帖子
            if (is_singular()) {
                $id = get_the_ID();
                if ($id && !in_array($id, $exclude_ids)) {
                    remove_meta_box('author', 'page', 'normal');
                    remove_meta_box('edit-comments-link', 'page', 'normal');
                    remove_meta_box('comments', 'page', 'normal');
                    remove_post_meta($id, '_wp_attachment_metadata');
                }
            }
        }
    }

    return $args;
}

add_action('init', 'exclude_last_posts');

// 执行过滤器以确保它正确工作
remove_action('wp_head', 'wp_print_scripts');
add_filter('body_class', 'wp_custom_body_classes');

WP_Query 示例(WordPress 5.0+)

function exclude_last_posts($query) {
    if (isset($_GET['exclude_tag'])) {
        $tag = $_GET['exclude_tag'];

        // 创建一个新的参数数组
        $new_query_args = [];

        // 添加新的参数到原始参数数组
        $new_query_args['post_type'] = $query->get('post_type');
        $new_query_args['post_status'] = $query->get('post_status');
        $new_query_args['orderby'] = $query->get('orderby');
        $new_query_args['meta_key'] = $query->get('meta_key');
        $new_query_args['meta_value'] = $query->get('meta_value');
        $new_query_args['post_tags'] = $query->get('post_tags');
        $new_query_args['post__not_in'] = $query->get('post__not_in');

        // 运行新查询
        $new_query = new WP_Query($new_query_args);

        // 删除匹配的帖子
        if ($new_query->have_posts()) {
            while ($new_query->have_posts()) {
                $new_query->the_post();

                // 在单个页面中删除最后一个帖子
                if (is_singular()) {
                    $id = get_the_ID();
                    if ($id && !in_array($id, $exclude_ids)) {
                        remove_meta_box('author', 'page', 'normal');
                        remove_meta_box('edit-comments-link', 'page', 'normal');
                        remove_meta_box('comments', 'page', 'normal');
                        remove_post_meta($id, '_wp_attachment_metadata');
                    }
                }
            }
        }

        // 清理旧数据
        clear_postdata();
        wp_reset_postdata();
    }
}

add_action('wp', 'exclude_last_posts');

以上就是从WordPress文章列表中排除最新文章的方法。通过使用WP_Query过滤器结合自定义函数或宏,可以根据具体需求灵活地实现这一功能。