首页 前端开发 wordpress

wp仿站函数

tts小陈 发布于 2026-08-04 09:12 更新于 2026-08-04 阅读 17 约 16,356 字 · 阅读 41 分钟
wordpress ·

✅首页

主题和插件url

<?php bloginfo('template_url'); ?> //调取当前主题目录url
<?php echo get_template_directory_uri(); ?> //调取当前主题目录url
<?php echo plugin_dir_url( __FILE__ );?> //调取当前插件目录url
<?php echo plugins_url( '/', __FILE__ ); ?> //调取当前插件目录url

调取头部

<?php get_header();?> //调取主题头部文件
<?php wp_head();?> //调取WordPress头部

调取指定头部

<?php get_header(后缀名称);?> //如header-fenlei.php  需要调取分类页头部则此处为get_header(fenlei)

调取底部

<?php get_footer();?> //调取主题底部文件
<?php wp_footer();?> //调取WordPress底部

文章

<?php the_title(); ?> //文章标题
<?php the_author(); ?>//调用作者姓名
<?php echo get_avatar( get_the_author_email(), 36 ); ?>//调用作者的Gravatar头像
<?php the_permalink() ?> //文章链接
<?php echo catch_that_image() ?> //文章缩略图
<?php the_time('Y-m-d'); ?> //文章日期
<?php the_content(''); ?> //文章内容
<?php the_excerpt(); ?> //文章摘要
<?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 200,'……'); ?> 
//文章简介,基于正文内容截取

文章日期英文

<?php the_time('M');?>

换成英文日期

<?php echo date('M',get_the_time('U'));?>

M为输出的日期格式

调取置顶文章

<?php  
$sticky = get_option('sticky_posts');  
rsort( $sticky );  
$sticky = array_slice( $sticky, 0, 3);
query_posts( array( 'posts_per_page' => 3,'post__in' => $sticky, 'ignore_sticky_posts' => 1 ) ); // 3为调取数量
if (have_posts()) :  
while (have_posts()) : the_post();  
?>
<li> <a href="<?php the_permalink() ?>" target="_blank"> <img class="j-lazy" src="<?php echo catch_that_image() ?>" data-original="<?php echo catch_that_image() ?>" alt="<?php the_title(); ?>"> </a> <span><?php the_title(); ?></span> </li>
       <?php endwhile; endif; ?>

调取指定id文章

<?php 
$jdwen = ''.sc_tsxcc('ts_jiaodian').'';//调取后台设置
$postsl = get_posts("numberposts=4&post_type=any&include=$jdwen"); //$jdwen为指定文章id
if($postsl) : foreach( $postsl as $post ) : setup_postdata( $post ); 
?>
<li class="topic"> <a class="topic-wrap" href="<?php the_permalink() ?>" target="_blank">
              <div class="cover-container"> <img class="j-lazy" src="<?php echo catch_that_image() ?>" data-original="<?php echo catch_that_image() ?>"> </div>
              <span><?php the_title(); ?></span> </a> </li>
<?php endforeach; endif; ?>

调取最新文章

<?php 
$zxpai = ''.sc_tsxcc('ts_paichu').''; //调取后台设置排除分类id
$zxwen = ''.sc_tsxcc('ts_shulaing').''; //调取后台设置数量
query_posts("cat=-$zxpai&posts_per_page=$zxwen&caller_get_posts=1"); ?>
<?php while (have_posts()) : the_post(); ?>
//文章代码
<?php endwhile; ?>

调用侧边栏

<?php get_sidebar();?>

调用友情链接

<?php  if ( is_home()) { ?>
 <?php wp_list_bookmarks('title_li=&categorize=0&orderby=link_id&limit=24'); ?>
 <?php } ?>

✅分类页

当前分类页名称

<?php single_cat_title(); ?>

当前分类链接

<?php echo esc_url(get_category_link(get_queried_object()->term_id)); ?>

不限分类循环代码

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

<?php endwhile;?>
<?php endif; ?>

可在上述循环中添加循环调取产品的标签

      <?php 
        // 获取当前文章的标签
        $tags = get_the_tags();
        if ($tags) : // 检查是否有标签
            foreach ($tags as $tag) : ?>
             <a href="<?php echo esc_url(get_tag_link($tag->term_id)); ?>">
                 <?php echo esc_html($tag->name); ?>
             </a>
            <?php endforeach; 
              endif; ?>

指定分类循环代码

<?php query_posts('cat=ID号&ignore_sticky_posts=1&showposts=显示数量'); ?>
<?php while (have_posts()) : the_post(); ?>
<?php endwhile;?>
<?php wp_reset_query(); ?>

指定分类名和分类链接

<?php echo get_cat_name( $catid );?> //分类名
<?php echo get_category_link( $catid );?> //分类链接
<?php echo category_description( $catid01 ); ?> //分类描述
<?php $cat = get_category(2);echo $cat->slug;?> //分类别名

调取随机文章

<?php
// 设置查询参数
$args = array(
    'posts_per_page' => 6, // 设置要显示的文章数量为 6
    'orderby' => 'rand', // 随机排序
    'ignore_sticky_posts' => 1, // 忽略置顶文章
);
// 创建自定义查询
$random_posts = new WP_Query($args);
// 检查是否有文章
if ($random_posts->have_posts()) : ?>
    <?php while ($random_posts->have_posts()) : $random_posts->the_post(); ?>
//文章代码
//文章代码
//文章代码
//文章代码
<?php else : ?>
    <p><?php _e('没有找到相关文章。'); ?></p>
<?php endif;
// 重置查询
wp_reset_postdata();
?>

✅根据栏目id循环调用栏目(栏目+文章)

<?php $display_categories =  explode(',',sc_tsxcc('唯一id') ); foreach ($display_categories as $category) { ?> //ts_index_dbtu_id为多个id,用英文半角逗号","隔开
<?php query_posts( array( 'showposts' => sc_tsxcc('唯一id'), 'cat' => $category, 'ignore_sticky_posts' => 1 ) ); ?>  //ts_index_lsb为调取数量,array组内可加其他调取条件
//根据输入id循环调取以下主代码  
<?php while (have_posts()) : the_post(); ?>
   //文章代码
          <?php the_permalink() ?> //文章链接
          <?php the_title(); ?> //文章标题
          <?php echo catch_that_image() ?> //文章缩略图
          <?php foreach((get_the_category()) as $category){echo get_category_link($category);}?> //文章所属分类链接
          <?php single_cat_title(); ?> //文章所属分类名称
          <?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 200,'……'); ?> //文章简介
          <?php the_time('Y-m-d'); ?> //文章发布时间
          <?php get_post_views($post -> ID); ?> //文章浏览量
          //文章代码
<?php endwhile;?>
<?php wp_reset_query(); ?>
//根据输入id循环调取主代码结束
<?php } ?>

✅根据栏目id循环调用(栏目)

循环栏目相关内容,如果需要循环栏目内的文章请使用上边的代码

<?php $display_categories =  explode(',',sc_tsxcc('唯一id') ); foreach ($display_categories as $category) { ?
              //栏目相关调用
               <?php echo get_cat_name($category);?>
                <?php echo strip_tags(category_description($category)); ?>
                 <?php echo get_category_link($category); ?>
 <?php } ?>

分类页调取文章

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
   //文章代码
          <?php the_permalink() ?> //文章链接
          <?php the_title(); ?> //文章标题
          <?php echo catch_that_image() ?> //文章缩略图
          <?php foreach((get_the_category()) as $category){echo get_category_link($category);}?> //文章所属分类链接
          <?php single_cat_title(); ?> //文章所属分类名称
          <?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 200,'……'); ?> //文章简介
          <?php the_time('Y-m-d'); ?> //文章发布时间
          <?php get_post_views($post -> ID); ?> //文章浏览量
          //文章代码
<?php endwhile;?>
<?php endif; ?>

✅分页

分页function代码

 //分页功能
function ts_paging() {
$p = 3;
if ( is_singular() ) return;
global $wp_query, $paged;
$max_page = $wp_query->max_num_pages;
if ( $max_page == 1 ) return; 
echo '<div"><ul>';
if ( empty( $paged ) ) $paged = 1;
if ( $paged > 1 ) p_link( 1, '首页' ); //显示首页
echo '<li class="prev-page">'; previous_posts_link('<'); echo '</li>';  //显示上一页和<
for( $i = $paged - $p; $i <= $paged + $p; $i++ ) {  
if ( $i > 0 && $i <= $max_page ) $i == $paged ? print "<li class=\"active\"><span>{$i}</span></li>" : p_link( $i );
}
echo '<li class="next-page">'; next_posts_link('>'); echo '</li>';  //显示下一页和>
p_link( $max_page, '尾页' );  //显示尾页
echo '<li><span>共 '.$max_page.' 页</span></li>';  //显示共**页
echo '</ul></div>';
}
function p_link( $i, $title = '' ) {
if ( $title == '' ) $title = "{$i}";
echo "<li><a href='", esc_html( get_pagenum_link( $i ) ), "'>{$title}</a></li>";
}
function p_curr_link( $i) {
echo '<li><span class="page-numbers current">'.$i.'</span></li>';
}
//分页功能

分页样式

.pagination {display: block; text-align: center; margin-top: 10px; padding-bottom: 20px}
.pagination{margin:30px 0;padding:0 10px;text-align:center;font-size:12px;display:block;border-radius:0}
.excerpts .pagination{margin-bottom: 10px;}
.pagination ul{display:inline-block !important;*display:inline;*zoom:1;margin-left:0;margin-bottom:0;padding:0}
.pagination ul > li{display:inline}
.pagination ul > li > a,.pagination ul > li > span{padding: 7px 8px;margin:0 2px;float:left;padding:5px 12px;background-color:#ddd;color:#666;border-radius:2px;opacity:.88}
.pagination ul > li > a:hover,.pagination ul > li > a:focus{opacity:1}
.pagination ul > .active > a,.pagination ul > .active > span{background-color:#1abc9c;color:#fff}
.pagination ul > .active > a,.pagination ul > .active > span{cursor:default}
.pagination ul > li > span,.pagination ul > .disabled > span,.pagination ul > .disabled > a,.pagination ul > .disabled > a:hover,.pagination ul > .disabled > a:focus{color:#999999;background-color:transparent;cursor:default}     

主题文件分页调取代码

<?php ts_paging();?>

✅页面

通过ID获取Page页面链接、名称

<?php echo get_page_link( ID );?> //获取Page页面链接
<?php echo get_page( ID )->post_title;?> //获取Page页面名称

更多用法

<?php echo get_page( ID )->post_title;?>
  • ID :页面ID号
  • post_author :作者ID
  • post_date :时间
  • post_content :页面内容
  • post_title :页面标题
  • post_excerpt :页面摘要
  • post_status :页面状态(发布,审核,加密等)
  • comment_status :评论状态(开启或关闭)
  • ping_status :Ping状态(开启或关闭)
  • post_password :页面密码
  • post_name :页面名称
  • post_modified :页面修改时间
  • post_parent :页面父级名称
  • guid :页面URl地址
  • menu_order :排序
  • post_type :类型Page
  • comment_count :评论数量

✅文章页

获取文章标签

<?php
$tags=g et_the_tags(); if ($tags) : // 检查是否有标签 foreach
($tags as $tag) : ?>
     <?php echo esc_url(get_tag_link($tag->term_id)); ?>  // 链接
            <?php echo esc_html($tag->name); ?>   // 名称
    <?php endforeach; endif; ?>

获取当前文章的分类

<?php
$categories = get_the_category();
if (!empty($categories)) {
    foreach ($categories as $category) {
        // 使用 get_category_link() 获取分类链接
        echo '<a href="' . esc_url(get_category_link($category->term_id)) . '">' . esc_html($category->name) . '</a> ';
    }
} else {
    // 如果没有分类,则输出提示信息
    echo '这篇文章没有分类。';
}
?>

面包屑导航

<?php echo '<a href="'.get_option('home').'">首页</a> / '; the_category(' > '); ?>

详情

<?php the_title(); ?> //文章标题
<?php echo get_the_author_meta( 'display_name', $post->post_author ); ?> //文章作者
<?php the_time('Y-m-d'); ?> //文章发布时间
<?php get_post_views($post -> ID); ?> //文章浏览次数
<?php the_content(''); ?> //文章内容
<?php the_tags('', ' ', ''); ?> //文章标签

上一篇

<?php
$prev_post = get_previous_post();
if (!empty( $prev_post )): ?>
        //上一篇代码  
            <?php echo get_permalink( $prev_post->ID ); ?> //上一篇文章链接
            <?php echo $prev_post->post_title; ?> //上一篇文章标题
            <?php the_time('Y-m-d'); ?> //上一篇文章发布时间
        //上一篇代码  
            <?php endif; ?>

下一篇

<?php
$next_post = get_next_post();
if (!empty( $next_post )): ?>
        //下一篇代码  
            <?php echo get_permalink( $next_post->ID ); ?> //上一篇文章链接
            <?php echo $next_post->post_title; ?> //上一篇文章标题
            <?php the_time('Y-m-d'); ?> //上一篇文章发布时间
        //下一篇代码  
            <?php endif; ?>

相关推荐

<?php
$cats = wp_get_post_categories($post->ID);
if ($cats) {
$args = array(
        'category__in' => array( $cats[0] ),
        'post__not_in' => array( $post->ID ),
        'showposts' => 6, //文章数量
        'ignore_sticky_posts' => 1
    );
query_posts($args);
if (have_posts()) : while (have_posts()) : the_post(); update_post_caches($posts); ?>
        //代码     
              <?php the_permalink(); ?> //文章链接
              <?php the_title(); ?> //文章标题
        //代码 
<?php endwhile; else : ?>
<?php endif; wp_reset_query(); } ?>

当前高亮

作用:

1、文章页内调取当前文章栏目下的所有文章标题并在当前文章上高亮显示。注意li处的样式(同理也可以用于各类相同效果展示)

<?php
$current_category = get_the_category();
if ($current_category) {
    $category_id = $current_category[0]->cat_ID;
    $current_post_id = get_the_ID();
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => -1,
        'cat' => $category_id
    );
    $posts_in_category = new WP_Query($args);
    if ($posts_in_category->have_posts()) {
        while ($posts_in_category->have_posts()) {
            $posts_in_category->the_post();
            ?>
            <li <?php if (get_the_ID() === $current_post_id) { echo 'class="current-item"'; } ?>><a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></li>
            <?php
        }
    }
}
wp_reset_postdata(); // 重置文章查询
?>

✅搜索页

搜索页面包屑/title

* 】的搜索结果

<?php if(is_search()) {
    $s = $_GET['s'];
    $s = strip_tags($s);
    echo "【".$s."】的搜索结果";
  }
  ?>

搜索代码

 <form  id="searchform" class="search-form" action="<?php bloginfo('url'); ?>/" method="get">
      <input type="text" class="keyword" placeholder="输入关键词搜索..." value="" name="s" id="s">
      <input type="submit" class="submit" value="">
    </form>

✅侧边栏

热门文章

<?php
$post_num = ''.sc_tsxcc('ts_syshulaing').''; // 后台设置调用条数
$args = array(
'post_password' => '',
'post_status' => 'publish', // 只选公开的文章.
'post__not_in' => array($post->ID),//排除当前文章
'ignore_sticky_posts' => 1, // 排除置顶文章.
'orderby' => 'comment_count', // 依评论数排序.
'posts_per_page' => $post_num
);
$query_posts = new WP_Query();
$query_posts->query($args);
while( $query_posts->have_posts() ) { $query_posts->the_post(); ?>
    //代码
      <?php the_title(); ?> //文章标题
      <?php the_permalink() ?> //文章链接
      <?php the_time('Y-m-d'); ?> //文章发布时间
      <?php echo catch_that_image() ?> //文章缩略图
     //代码
  <?php } wp_reset_query();?>

随机文章

方法一:foreach循环

<?php
$post_num = ''.sc_tsxcc('ts_sysjshulaing').'';
$args = array( 'numberposts' => $post_num, 'orderby' => 'rand', 'post_status' => 'publish' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
//代码
      <?php the_title(); ?> //文章标题
      <?php the_permalink() ?> //文章链接
      <?php the_time('Y-m-d'); ?> //文章发布时间
      <?php echo catch_that_image() ?> //文章缩略图
 //代码
<?php endforeach; ?>

方法二:while循环

<?php
$post_num = ''.sc_tsxcc('ts_syshulaing').''; // 设置调用条数
$args = array(
'caller_get_posts' => 1, // 排除置顶文章.
'orderby' => rand, // 依评论数排序.
'posts_per_page' => $post_num
);
query_posts($args); ?>
<?php while (have_posts()) : the_post(); ?>
<li>
<a target="_blank" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="title"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>

标签云

<?php wp_tag_cloud( $args ); ?>

✅其他

网站名称

<?php bloginfo('name'); ?>

主题当前目录

<?php bloginfo('template_directory'); ?>  //引用文件
<?php bloginfo('template_url'); ?>        //引用资源(如样式表、脚本、图片等)

使用 bloginfo('template_directory') 来包含一个 PHP 文件:

include( get_bloginfo('template_directory') . '/includes/my-script.php' );

使用 bloginfo('template_url') 来引入一个 CSS 文件:

<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/style.css">

bloginfo('template_directory'): 返回主题的文件系统路径,适用于服务器文件操作。 bloginfo('template_url'): 返回主题的 URL,适用于在网页中引用资源。

✅创建分类时选择模板

作用:为不同分类设置不同的模板或者同一分类下选择使用同一模板

第一步,创建模板文件

模板文件顶部添加代码

<?php
/*
Template Name: 独特优势
*/
?>

第二步,将如下代码添加到当前主题function下

// 分类选择模板
class Select_Category_Template{
    public function __construct() {
        add_filter( 'category_template', array($this,'get_custom_category_template' ));
        add_action ( 'edit_category_form_fields', array($this,'category_template_meta_box'));
        add_action( 'category_add_form_fields', array( &$this, 'category_template_meta_box') );
        add_action( 'created_category', array( &$this, 'save_category_template' ));
        add_action ( 'edited_category', array($this,'save_category_template'));
        do_action('Custom_Category_Template_constructor',$this);
    }

    // 添加表单到分类编辑页面
    public function category_template_meta_box( $tag ) {
        $t_id = $tag->term_id;
        $cat_meta = get_option( "category_templates");
        $template = isset($cat_meta[$t_id]) ? $cat_meta[$t_id] : false;
        ?>
        <tr class="form-field">
            <th scope="row" valign="top"><label for="cat_Image_url"><?php _e('Category Template'); ?></label></th>
            <td>
                <select name="cat_template" id="cat_template">
                    <option value='default'><?php _e('必须选择分类模板'); ?></option>
                    <?php page_template_dropdown($template); ?>
                </select>
                <br />
                <span class="description"><?php _e('为此分类选择一个模板'); ?></span>
            </td>
        </tr>
        <?php
        do_action('Custom_Category_Template_ADD_FIELDS',$tag);
    }
    // 保存表单
    public function save_category_template( $term_id ) {
        if ( isset( $_POST['cat_template'] )) {
            $cat_meta = get_option( "category_templates");
            $cat_meta[$term_id] = $_POST['cat_template'];
            update_option( "category_templates", $cat_meta );
            do_action('Custom_Category_Template_SAVE_FIELDS',$term_id);
        }
    }
    // 处理选择的分类模板
    function get_custom_category_template( $category_template ) {
        $cat_ID = absint( get_query_var('cat') );
        $cat_meta = get_option('category_templates');
        if (isset($cat_meta[$cat_ID]) && $cat_meta[$cat_ID] != 'default' ){
            $temp = locate_template($cat_meta[$cat_ID]);
            if (!empty($temp))
                return apply_filters("Custom_Category_Template_found",$temp);
        }
        return $category_template;
    }
}
$cat_template = new Select_Category_Template();

完成上述操作,在创建分类时即可选择模板。

同分类随机文章

<?php
$cat = get_the_category();
foreach($cat as $key=>$category){
$catid = $category->term_id;}
$args = array('orderby' => 'rand','showposts' => 8,'cat' => $catid ); // 显示篇数
$query_posts = new WP_Query();
$query_posts->query($args);
while ($query_posts->have_posts()) : $query_posts->the_post();?>
// 代码
<?php the_permalink(); ?> // 文章链接
<?php the_title(); ?> // 文章标题
// 代码
<?php endwhile;?>
<?php wp_reset_query(); ?>

指定分类文章

<?php
    $args=array(
        'cat' => 1,   // 分类ID
        'posts_per_page' => 10, // 显示篇数
    );
    query_posts($args);
    if(have_posts()) : while (have_posts()) : the_post();
?>
   //代码
        <?php the_permalink(); ?> // 文章链接
        <?php the_title(); ?> // 文章标题
   //代码
<?php  endwhile; endif; wp_reset_query(); ?>

上传图片自动重命名

方法一、按时间重命名
//上传文件图片按时间重命名重命名
function git_upload_filter($file) {
    $time = date("YmdHis");
    $file['name'] = $time . "" . mt_rand(1, 100) . "." . pathinfo($file['name'], PATHINFO_EXTENSION);
    return $file;
}
add_filter('wp_handle_upload_prefilter', 'git_upload_filter');
方法二、用 MD5 加密生成数字并重命名
//上传文件图片 MD5 加密重命名
function rename_filename($filename) {
    $info = pathinfo($filename);
    $ext = emptyempty($info['extension']) ? '' : '.' . $info['extension'];
    $name = basename($filename, $ext);
    return substr(md5($name), 0, 20) . $ext;
}
add_filter('sanitize_file_name', 'rename_filename', 10);
💬 留言 共 0 条 · 登录后可留言
还没有留言,来抢沙发~