全新升级 v1.0.3 | 更强大、更灵活

WordPress 原生内容
通用展示工具

支持自定义文章类型、分类筛选和分页功能,小白也能轻松实现复杂内容展示

什么是这个工具?

一款为WordPress小白设计的内容展示解决方案,无需专业开发知识

原生兼容

完美支持WordPress自带的文章、页面、分类体系,v1.0.3新增自定义文章类型支持

安全可靠

自动过滤危险参数,完善的错误处理机制,避免因配置错误导致的页面崩溃

灵活扩展

支持高级筛选、分页功能、自定义字段展示,可根据需求调整HTML结构和样式

性能优化

增强的查询缓存机制,支持手动清除缓存,大幅减少数据库请求,提升页面加载速度

适用场景

博客文章列表、企业新闻展示、产品分类页、"关于我们"页面内容、自定义字段数据展示、 带分页的内容浏览、多条件筛选展示...所有需要灵活调用WordPress内容的场景

v1.0.3 新特性

相比v1.0.2的核心升级点

自定义文章类型支持

新增对自定义文章类型的支持,可通过参数指定任意自定义文章类型,示例:

// 调用自定义文章类型
native_content_display(array(
    'content_type' => 'custom',
    'post_type' => 'product', // 自定义文章类型
    'target' => '12' // 分类ID或slug
));

高级筛选功能

支持按标签、作者、日期范围等多条件筛选内容,示例:

// 多条件筛选示例
'show_fields' => array('title', 'date', 'excerpt'),
'tag' => 'news', // 按标签筛选
'author' => 3, // 按作者ID筛选
'date_from' => '2023-01-01', // 开始日期
'date_to' => '2023-12-31' // 结束日期

完善的分页功能

新增自动分页导航生成功能,支持自定义分页样式和显示数量,通过简单配置即可实现专业分页效果

增强缓存管理

添加手动清除缓存函数,支持按类型清除特定缓存,解决内容更新后缓存同步问题:

// 清除所有缓存
native_content_clear_cache();

// 清除特定类型缓存
native_content_clear_cache('category', 'news');

核心代码(v1.0.3)

复制到主题的 functions.php 末尾即可使用

functions.php 代码

最新版本:v1.0.3
<?php /**
* WordPress 原生内容通用展示工具 
* 版本:1.0.3(含自定义文章类型+高级筛选+分页功能)
* 适用场景:无需复杂开发,轻松展示原生文章、页面、分类及自定义文章类型内容
* 使用说明:复制到主题 functions.php 后,按下方示例调用即可 
*/

/**
* 原生内容展示主函数 
* @param array $args 自定义参数(可选,不填则用默认值) 
* @return string 生成的HTML内容(含错误提示) 
*/
function native_content_display($args = array()) {
    // 【1. 参数定义(小白可直接改默认值,或调用时传参覆盖)】 
    $defaults = array(
        // 核心参数(必须设置,决定查询类型) 
        'content_type' => 'post', // 内容类型: 'post'/'page'/'category'/'custom'
        'target' => '', // 目标标识:ID或slug
        'post_type' => 'post', // 自定义文章类型(仅content_type为'custom'时有效)
        
        // 列表参数(仅content_type为'category'或'custom'时有效) 
        'posts_per_page' => 5, // 显示数量:-1=全部
        'order' => 'desc', // 排序方向:'desc'/'asc'
        'orderby' => 'date', // 排序依据:'date'/'title'/'comment_count'/'rand'
        'offset' => 0, // 跳过的内容数量(用于分页)
        
        // 筛选参数(v1.0.3新增)
        'tag' => '', // 按标签筛选(标签ID或slug)
        'author' => '', // 按作者筛选(用户ID)
        'date_from' => '', // 开始日期(格式:Y-m-d)
        'date_to' => '', // 结束日期(格式:Y-m-d)
        
        // 显示字段(支持默认字段和自定义字段meta:xxx)
        'show_fields' => array(
            'title', // 标题(带链接) 
            'date', // 发布日期 
            'excerpt' // 摘要
        ),
        // 可选默认字段: 'author'/'thumbnail'/'content'
        // 自定义字段格式: 'meta:字段名' (如 'meta:phone' 显示phone字段)
        
        // 分页参数(v1.0.3新增)
        'pagination' => true, // 是否显示分页
        'pagination_class' => 'content-pagination', // 分页容器CSS类
        'pagination_prev_text' => '上一页', // 上一页文本
        'pagination_next_text' => '下一页', // 下一页文本
        
        // 样式容器参数
        'wrap_tag' => 'ul', // 外层容器标签
        'wrap_class' => 'native-content', // 外层容器CSS类
        'item_tag' => 'li', // 单条内容标签
        'item_class' => 'content-item', // 单条内容CSS类
        
        // 缓存参数
        'cache_time' => 3600, // 缓存时间(秒),0=不缓存
        'date_format' => 'Y-m-d' // 日期格式
    );

    // 【2. 参数处理(自动过滤错误值)】
    $args = wp_parse_args($args, $defaults); 
    
    // 安全过滤
    $args['content_type'] = in_array($args['content_type'], ['post', 'page', 'category', 'custom']) ? $args['content_type'] : 'post';
    $args['order'] = in_array($args['order'], ['desc', 'asc']) ? $args['order'] : 'desc'; 
    $args['orderby'] = in_array($args['orderby'], ['date', 'title', 'comment_count', 'rand']) ? $args['orderby'] : 'date';
    $args['posts_per_page'] = absint($args['posts_per_page']);
    $args['offset'] = absint($args['offset']);
    $args['cache_time'] = absint($args['cache_time']);
    $args['pagination'] = (bool)$args['pagination'];
    
    $allowed_tags = ['div', 'ul', 'ol', 'li', 'section']; 
    $args['wrap_tag'] = in_array($args['wrap_tag'], $allowed_tags) ? $args['wrap_tag'] : 'ul'; 
    $args['item_tag'] = in_array($args['item_tag'], $allowed_tags) ? $args['item_tag'] : 'li';

    // 空参数容错
    if (empty($args['target']) && in_array($args['content_type'], ['category', 'custom'])) {
        return '<p class="content-error">请填写target参数(如分类slug、文章ID)</p>';
    }

    // 【3. 缓存处理】
    $cache_key = 'native_content_' . md5(serialize($args));
    $cached_content = $args['cache_time'] > 0 ? get_transient($cache_key) : false;
    
    if ($cached_content !== false) {
        return $cached_content; // 返回缓存内容
    }

    // 【4. 查询内容】
    $content_list = array();
    $total_posts = 0; // 总记录数,用于分页(v1.0.3新增)
    
    // 4.1 查分类下的文章列表
    if ($args['content_type'] == 'category') {
        $cat_id = 0;
        if (is_numeric($args['target'])) {
            $cat_id = $args['target'];
            if (!term_exists((int)$cat_id, 'category')) {
                return '<p class="content-error">未找到分类(检查target是否正确)</p>';
            }
        } else {
            $category = get_category_by_slug($args['target']); 
            $cat_id = $category ? $category->term_id : 0;
        }

        if (!$cat_id) {
            return '<p class="content-error">未找到分类(检查target是否正确)</p>';
        }

        $query_args = array(
            'cat' => $cat_id,
            'posts_per_page' => $args['posts_per_page'], 
            'order' => $args['order'],
            'orderby' => $args['orderby'],
            'offset' => $args['offset'],
            'post_type' => 'post', 
            'post_status' => 'publish', 
            'suppress_filters' => true,
            'no_found_rows' => !$args['pagination'] // 如果不需要分页,不查询总记录数
        );
        
        // 添加筛选条件(v1.0.3新增)
        $query_args = native_content_add_filters($query_args, $args);
        
        $query = new WP_Query($query_args);
        $content_list = $query->have_posts() ? $query->posts : array();
        $total_posts = $query->found_posts; // 获取总记录数

    // 4.2 查单篇文章 
    } elseif ($args['content_type'] == 'post') {
        $post = null;
        if (is_numeric($args['target'])) {
            $post = get_post((int)$args['target']);
        } else {
            $post = get_page_by_path($args['target'], OBJECT, 'post');
        }
        if ($post && is_a($post, 'WP_Post') && $post->post_type === 'post' && $post->post_status === 'publish') {
            $content_list = array($post);
        } else {
            return '<p class="content-error">未找到文章(检查target是否正确)</p>';
        }

    // 4.3 查单页 
    } elseif ($args['content_type'] == 'page') {
        $page = null;
        if (is_numeric($args['target'])) {
            $page = get_post((int)$args['target']);
        } else {
            $page = get_page_by_path($args['target'], OBJECT, 'page');
        }
        if ($page && is_a($page, 'WP_Post') && $page->post_type === 'page' && $page->post_status === 'publish') {
            $content_list = array($page);
        } else {
            return '<p class="content-error">未找到单页(检查target是否正确)</p>';
        }
        
    // 4.4 查自定义文章类型(v1.0.3新增)
    } elseif ($args['content_type'] == 'custom') {
        // 验证自定义文章类型是否存在
        if (!post_type_exists($args['post_type'])) {
            return '<p class="content-error">不存在的自定义文章类型: ' . esc_html($args['post_type']) . '</p>';
        }
        
        $tax_query = array();
        // 如果指定了分类目标,添加分类筛选
        if (!empty($args['target'])) {
            $taxonomy = $args['post_type'] === 'post' ? 'category' : $args['post_type'] . '_category';
            // 检查分类法是否存在
            if (!taxonomy_exists($taxonomy)) {
                $taxonomy = 'category'; // 回退到默认分类法
            }
            
            $term_id = 0;
            if (is_numeric($args['target'])) {
                $term_id = $args['target'];
                if (!term_exists((int)$term_id, $taxonomy)) {
                    return '<p class="content-error">未找到指定分类(检查target是否正确)</p>';
                }
            } else {
                $term = get_term_by('slug', $args['target'], $taxonomy);
                $term_id = $term ? $term->term_id : 0;
            }
            
            if ($term_id) {
                $tax_query[] = array(
                    'taxonomy' => $taxonomy,
                    'field' => 'term_id',
                    'terms' => $term_id
                );
            }
        }
        
        $query_args = array(
            'post_type' => $args['post_type'],
            'posts_per_page' => $args['posts_per_page'],
            'order' => $args['order'],
            'orderby' => $args['orderby'],
            'offset' => $args['offset'],
            'post_status' => 'publish',
            'suppress_filters' => true,
            'no_found_rows' => !$args['pagination'],
            'tax_query' => $tax_query
        );
        
        // 添加筛选条件
        $query_args = native_content_add_filters($query_args, $args);
        
        $query = new WP_Query($query_args);
        $content_list = $query->have_posts() ? $query->posts : array();
        $total_posts = $query->found_posts;
    }

    // 无内容提示
    if (empty($content_list)) {
        return '<p class="content-empty">未找到相关内容</p>';
    }

    // 【5. 生成HTML】
    $output = '<' . $args['wrap_tag'] . ' class="' . esc_attr($args['wrap_class']) . '">';
    foreach ($content_list as $item) {
        $output .= '<' . $args['item_tag'] . ' class="' . esc_attr($args['item_class']) . '">';
        
        foreach ($args['show_fields'] as $field) {
            // 处理自定义字段
            if (strpos($field, 'meta:') === 0) {
                $meta_key = substr($field, 5);
                $meta_value = get_post_meta($item->ID, $meta_key, true);
                
                // 支持数组类型的自定义字段(v1.0.3新增)
                if (is_array($meta_value) && !empty($meta_value)) {
                    $output .= '<div class="content-meta-' . esc_attr($meta_key) . '">';
                    $output .= '<span class="meta-label">' . esc_html(ucfirst($meta_key)) . ': </span>';
                    $output .= '<ul class="meta-list">';
                    foreach ($meta_value as $value) {
                        $output .= '<li>' . esc_html($value) . '</li>';
                    }
                    $output .= '</ul></div>';
                } elseif ($meta_value) {
                    $output .= '<p class="content-meta-' . esc_attr($meta_key) . '">' 
                        . esc_html(ucfirst($meta_key) . ': ' . $meta_value) . '</p>';
                }
                continue;
            }

            // 处理默认字段
            switch ($field) {
                case 'title':
                    $permalink = get_permalink($item->ID);
                    $title = get_the_title($item->ID);
                    $output .= '<h3 class="content-title"><a href="' . esc_url($permalink) . '">' 
                        . (empty($title) ? '无标题' : esc_html($title)) . '</a></h3>';
                    break;

                case 'date':
                    $output .= '<p class="content-date">发布时间:' 
                        . esc_html(get_the_date($args['date_format'], $item->ID)) . '</p>';
                    break;

                case 'excerpt':
                    $excerpt = has_excerpt($item->ID) ? get_the_excerpt($item->ID) : wp_trim_words(strip_tags($item->post_content), 30, '...');
                    $output .= '<p class="content-excerpt">' . esc_html($excerpt) . '</p>';
                    break;

                case 'author':
                    $author = get_the_author_meta('display_name', $item->post_author); 
                    $author_url = get_author_posts_url($item->post_author);
                    $output .= '<p class="content-author">作者:<a href="' . esc_url($author_url) . '">' 
                        . esc_html($author ?: '未知') . '</a></p>';
                    break;

                case 'thumbnail':
                    if (function_exists('has_post_thumbnail') && has_post_thumbnail($item->ID)) {
                        $output .= '<div class="content-thumb">' 
                            . get_the_post_thumbnail($item->ID, 'medium', array(
                                'class' => 'thumb-img', 
                                'alt' => esc_attr(get_the_title($item->ID))
                            )) . '</div>';
                    } else {
                        $output .= '<p class="thumb-tip">未设置缩略图</p>';
                    } 
                    break;

                case 'content':
                    $content = apply_filters('the_content', $item->post_content); 
                    $output .= '<div class="content-full">' . $content . '</div>';
                    break;
            }
        }
        $output .= '</' . $args['item_tag'] . '>';
    }
    $output .= '</' . $args['wrap_tag'] . '>';
    
    // 生成分页导航(v1.0.3新增)
    if ($args['pagination'] && $args['posts_per_page'] > 0 && $total_posts > $args['posts_per_page']) {
        $output .= native_content_generate_pagination($total_posts, $args);
    }

    // 【6. 清理查询与缓存】
    if (in_array($args['content_type'], ['category', 'custom'])) {
        wp_reset_postdata();
    }
    
    // 存入缓存
    if ($args['cache_time'] > 0) {
        set_transient($cache_key, $output, $args['cache_time']);
    }

    return $output;
}

/**
* 添加筛选条件的辅助函数(v1.0.3新增)
*/
function native_content_add_filters($query_args, $args) {
    // 标签筛选
    if (!empty($args['tag'])) {
        $query_args['tag'] = $args['tag'];
    }
    
    // 作者筛选
    if (!empty($args['author']) && is_numeric($args['author'])) {
        $query_args['author'] = $args['author'];
    }
    
    // 日期范围筛选
    if (!empty($args['date_from']) || !empty($args['date_to'])) {
        $date_query = array('relation' => 'AND');
        
        if (!empty($args['date_from']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $args['date_from'])) {
            $date_query[] = array(
                'after' => $args['date_from'],
                'inclusive' => true
            );
        }
        
        if (!empty($args['date_to']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $args['date_to'])) {
            $date_query[] = array(
                'before' => $args['date_to'],
                'inclusive' => true
            );
        }
        
        $query_args['date_query'] = $date_query;
    }
    
    return $query_args;
}

/**
* 生成分页导航的辅助函数(v1.0.3新增)
*/
function native_content_generate_pagination($total_posts, $args) {
    $total_pages = ceil($total_posts / $args['posts_per_page']);
    $current_page = ($args['offset'] / $args['posts_per_page']) + 1;
    $base_url = get_permalink();
    
    // 构建分页URL
    $pagination_base = trailingslashit($base_url) . '%_%';
    if (strpos($base_url, '?') !== false) {
        $pagination_base = $base_url . '&page=%#%';
    } else {
        $pagination_base = $base_url . '?page=%#%';
    }
    
    // 生成分页链接
    $pagination = paginate_links(array(
        'base' => $pagination_base,
        'format' => '?page=%#%',
        'current' => $current_page,
        'total' => $total_pages,
        'prev_text' => $args['pagination_prev_text'],
        'next_text' => $args['pagination_next_text'],
        'type' => 'array',
        'mid_size' => 2,
        'end_size' => 1
    ));
    
    if (empty($pagination)) {
        return '';
    }
    
    $output = '<div class="' . esc_attr($args['pagination_class']) . '"><ul>';
    foreach ($pagination as $page_link) {
        $output .= '<li class="page-item' . (strpos($page_link, 'current') !== false ? ' active' : '') . '">' . $page_link . '</li>';
    }
    $output .= '</ul></div>';
    
    return $output;
}

/**
* 清除缓存的函数(v1.0.3新增)
* @param string $content_type 内容类型,留空则清除所有
* @param string $target 目标标识,留空则清除该类型所有缓存
*/
function native_content_clear_cache($content_type = '', $target = '') {
    global $wpdb;
    
    if (empty($content_type)) {
        // 清除所有缓存
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_native_content_%'");
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_timeout_native_content_%'");
    } else {
        // 清除特定类型的缓存
        $like = '_transient_native_content_%' . md5('s:13:"content_type";s:' . strlen($content_type) . ':"' . $content_type . '"');
        
        if (!empty($target)) {
            $like .= '%' . md5('s:6:"target";s:' . strlen($target) . ':"' . $target . '"');
        }
        
        $wpdb->query($wpdb->prepare(
            "DELETE FROM $wpdb->options WHERE option_name LIKE %s",
            $like . '%'
        ));
        $wpdb->query($wpdb->prepare(
            "DELETE FROM $wpdb->options WHERE option_name LIKE %s",
            '_transient_timeout_' . substr($like, 10) . '%'
        ));
    }
    
    return true;
}

代码更新说明

  • 新增自定义文章类型支持,通过 content_type => 'custom'post_type 参数调用
  • 添加高级筛选功能,支持按标签、作者、日期范围筛选内容
  • 新增自动分页功能,可自定义分页样式和导航文本
  • 添加 native_content_clear_cache() 函数,支持手动清除缓存
  • 支持数组类型的自定义字段展示,自动转换为列表形式

可视化配置工具

选择参数生成对应的调用代码(无需懂PHP)

// 请配置参数并点击生成按钮
native_content_display(array(
    'content_type' => 'post',
    'target' => '填写ID或Slug',
    'show_fields' => array('title', 'date', 'excerpt'),
    'pagination' => true
));

使用提示

  • 1. 将生成的代码粘贴到主题模板文件(如page.php、single.php)
  • 2. 如需在文章/页面中使用,需配合"插入PHP代码"类插件
  • 3. 内容更新后可使用 native_content_clear_cache() 清除缓存
  • 4. 调用自定义文章类型时,请确保该类型已存在

常用调用示例

以下是几种常见场景的调用代码示例

1. 显示单篇文章

调用ID为123的文章,显示标题、缩略图和全文:

native_content_display(array(
    'content_type' => 'post',
    'target' => 123, // 文章ID
    'show_fields' => array('title', 'thumbnail', 'content')
));

2. 显示分类文章列表

调用分类slug为"news"的文章,每页显示10篇,带分页:

native_content_display(array(
    'content_type' => 'category',
    'target' => 'news', // 分类slug
    'posts_per_page' => 10,
    'orderby' => 'date',
    'order' => 'desc',
    'show_fields' => array('title', 'date', 'author', 'excerpt'),
    'pagination' => true,
    'pagination_prev_text' => '上一页',
    'pagination_next_text' => '下一页'
));

3. 调用自定义文章类型

调用产品类型文章,显示自定义字段:

native_content_display(array(
    'content_type' => 'custom',
    'post_type' => 'product', // 自定义文章类型
    'target' => 'electronics', // 产品分类
    'posts_per_page' => 8,
    'orderby' => 'title',
    'order' => 'asc',
    'show_fields' => array(
        'title', 
        'thumbnail',
        'meta:price', // 价格自定义字段
        'meta:stock'  // 库存自定义字段
    ),
    'pagination' => true
));

4. 多条件筛选

筛选2023年作者ID为3的新闻:

native_content_display(array(
    'content_type' => 'category',
    'target' => 'news',
    'posts_per_page' => 6,
    'author' => 3, // 作者ID
    'date_from' => '2023-01-01',
    'date_to' => '2023-12-31',
    'tag' => 'featured', // 带featured标签
    'show_fields' => array('title', 'date', 'excerpt'),
    'pagination' => true
));

常见问题

使用过程中可能遇到的问题及解决方法