加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > CMS系统 > wordpress > 正文

几个实用的 WordPress 代码片段

发布时间:2020-12-14 14:42:03 所属栏目:wordpress 来源:网络整理
导读:贴几个最近用到 WordPress 的代码片段,代码均搜集于网络,使用方式都是添加到主题的 functions.php 文件。 Talk is cheap. Show me the code. —— Linus Torvalds 搜索结果页面关键字高亮 为搜索结果页中的标题和正文的关键字添加 highlight 类,然后你就

贴几个最近用到 WordPress 的代码片段,代码均搜集于网络,使用方式都是添加到主题的 functions.php 文件。

“Talk is cheap. Show me the code.” —— Linus Torvalds

搜索结果页面关键字高亮

为搜索结果页中的标题和正文的关键字添加 highlight 类,然后你就可以通过 CSS 设定高亮样式了。

',$text);
    }
    return $text;
}
add_filter( 'the_title','qq52o_highlight_search_keywords' );
add_filter( 'the_excerpt','qq52o_highlight_search_keywords' );

搜索关键字为空时自动跳转到首页

默认情况下,如果关键字为空,WordPress 会列出所有的文章。谁会这么无聊… 不如自动跳转到首页。

关闭文章的标签功能

用不到标签,留着碍眼?去掉吧,就这么简单粗暴。

清理 WordPress 菜单中的 classes

WordPress 菜单默认会输出一堆然并卵的 classes。如果你有洁癖,可以只保留你觉得有用的 classes,比如我觉得 current-menu-itemmenu-item-has-children 最有用了。

自动设置文章的第一张图为特色图像

懒得每次手动设置特色图像?这段代码可以自动把文章中上传的第一张图片设置为特色图像。(不支持外链图片)

ID);
    if (!$already_has_thumb)  {
        $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
        if ($attached_image) {
            foreach ($attached_image as $attachment_id => $attachment) {
                set_post_thumbnail($post->ID,$attachment_id);
            }
        }
    }
}
add_action( 'the_post','qq52o_autoset_featured_image' );
add_action( 'save_post','qq52o_autoset_featured_image' );
add_action( 'draft_to_publish','qq52o_autoset_featured_image' );
add_action( 'new_to_publish','qq52o_autoset_featured_image' );
add_action( 'pending_to_publish','qq52o_autoset_featured_image' );
add_action( 'future_to_publish','qq52o_autoset_featured_image' );

添加短代码

这段代码是把 [attachment id="1,2,3"] 输出为一个附件列表。

foreach ($ids as $id) {
$url = wp_get_attachment_url( $id );
$name = basename($url);
$html .= '
  • <a class="file" href="' . $url . '" target="_blank">' . basename($url) . '
  • ';
    }
    ? return '<div class="attachment-box"><h5 class="title">附件:
      ' . $html . '
    ';
    }
    add_shortcode( 'attachment','qq52o_attachment_shortcode' );

    (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

      推荐文章
        热点阅读