WordPress使用久了,给主题添加的功能较多,年纪大了,怕忘记,就记下来,方便自己寻找,本次代码均添加在主题文件的functions.php中。
1、移除站点健康仪表盘小工具,代码来自WordPress大学
/**
* 移除 工具-站点健康 菜单
*/
function wpkj_remove_site_health_menu(){
remove_submenu_page( 'tools.php','site-health.php' );
}
add_action( 'admin_menu', 'wpkj_remove_site_health_menu' );
2、更新文章的自动更新时间为当前时间
//时间
function update_post_publish_date_on_update( $post_id, $post, $update ) {
global $wpdb;
// 跳过:自动保存、修订、未发布、非文章
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( wp_is_post_revision( $post_id ) ) return;
if ( $post->post_type !== 'post' ) return;
if ( ! $update ) return;
// 检查是否已执行过(避免重复)
if ( get_post_meta( $post_id, '_custom_updated_date_once', true ) ) {
return;
}
// 获取当前时间(本地时间)
$current_time = current_time( 'mysql' );
$current_time_gmt = get_gmt_from_date( $current_time );
// 使用直接 SQL 更新 post_date,避免触发额外钩子
$wpdb->update(
$wpdb->posts,
array(
'post_date' => $current_time,
'post_date_gmt' => $current_time_gmt
),
array( 'ID' => $post_id )
);
// 设置标记,避免重复更新
update_post_meta( $post_id, '_custom_updated_date_once', 1 );
// 可选:删除标记(只在这次保存中有效)
add_action( 'shutdown', function() use ( $post_id ) {
delete_post_meta( $post_id, '_custom_updated_date_once' );
} );
}
add_action( 'save_post', 'update_post_publish_date_on_update', 10, 3 );
3、给网站添加CDN,代码来自zhang.ge
// **
// * 原文地址:https://zhang.ge/4905.html
// **
function QiNiuCDN(){
function Rewrite_URI($html){
/* 前面自己的域名域名,后面是需要加速的静态文件类型,使用分隔符 | 隔开即可 */
$pattern ='/https:\/\/(www\.|)5v13\.com\/wp-([^"\']*?)\.(jpg|webp|js|gif|png|jpeg)/i';
/* CDN 地址,请自行替换成腾讯、阿里等cdn地址 */
$replacement = 'https://cdn.5v13.com/wp-$2.$3';
$html = preg_replace($pattern, $replacement,$html);
return $html;
}
if(!is_admin()){
ob_start("Rewrite_URI");
}
}
add_action('init', 'QiNiuCDN');
4、给经典编辑器添加首行缩进,同时需要添加js,js路径我这里为主题目录下的/js/indent-first-line.js,可以根据自己的实际情况修改
// 添加自定义按钮到经典编辑器
function add_indent_first_line_button($buttons) {
array_push($buttons, 'indent_first_line');
return $buttons;
}
add_filter('mce_buttons', 'add_indent_first_line_button');
// 注册并添加自定义 TinyMCE 插件
function register_indent_first_line_plugin($plugin_array) {
$plugin_array['indent_first_line'] = get_template_directory_uri() . '/js/indent-first-line.js';
return $plugin_array;
}
add_filter('mce_external_plugins', 'register_indent_first_line_plugin');
js代码如下,请自行创建
(function() {
tinymce.PluginManager.add('indent_first_line', function(editor) {
editor.addButton('indent_first_line', {
text: '首行缩进',
icon: false,
onclick: function() {
var selectedNode = editor.selection.getNode();
editor.dom.setStyle(selectedNode, 'text-indent', '2em');
}
});
});
})();
5.统计网站所有的草稿并列出,搭配https://seo.juziseo.com/tools/kai/
// 添加后台菜单项:草稿编辑链接
add_action('admin_menu', function () {
add_menu_page(
'草稿链接',
'草稿链接',
'edit_posts',
'theme-draft-links',
'theme_draft_links_page_callback',
'dashicons-media-code',
25
);
});
// 页面输出函数(含复制按钮)
function theme_draft_links_page_callback() {
if (!current_user_can('edit_posts')) {
wp_die(__('你无权限查看此页面。'));
}
echo '<div class="wrap">';
echo '<h1>草稿编辑链接</h1>';
// 使用 transient 缓存草稿链接
$cache_key = 'cached_draft_edit_links';
$cached_links = get_transient($cache_key);
if ($cached_links === false) {
$query = new WP_Query(array(
'post_status' => 'draft',
'post_type' => 'post',
'posts_per_page' => -1,
'fields' => 'ids',
'no_found_rows' => true,
'cache_results' => true,
));
if (!empty($query->posts)) {
$links = array_map(function ($post_id) {
return esc_url(get_edit_post_link($post_id));
}, $query->posts);
$cached_links = implode("\n", $links);
} else {
$cached_links = '';
}
set_transient($cache_key, $cached_links, 60);
}
if (empty($cached_links)) {
echo '<p>暂无草稿文章。</p>';
} else {
echo '<p>以下是草稿文章的编辑链接:</p>';
// 复制按钮
echo '<button id="copyLinksBtn" class="button button-primary" style="margin-bottom:10px;">复制全部</button>';
echo '<span id="copyStatus" style="margin-left:10px;"></span>';
// 链接显示区域
echo '<pre id="linksOutput" style="background:#f5f5f5; padding:15px; border-radius:6px; overflow:auto; font-size:13px;"><code>';
echo esc_html($cached_links);
echo '</code></pre>';
// JS 脚本:复制逻辑
echo <<<HTML
<script>
document.getElementById('copyLinksBtn').addEventListener('click', function() {
const content = document.getElementById('linksOutput').innerText;
navigator.clipboard.writeText(content).then(function() {
document.getElementById('copyStatus').innerText = "已复制!";
setTimeout(() => document.getElementById('copyStatus').innerText = "", 2000);
}, function() {
document.getElementById('copyStatus').innerText = "复制失败!";
});
});
</script>
HTML;
}
echo '</div>';
}
6.在WordPress文章后台添加一个复制按钮,快速复制一篇并添加为草稿
// 复制文章
function zm_clone_post_as_draft() {
global $wpdb;
if (! ( isset( $_GET['post']) || isset( $_POST['post']) || ( isset($_REQUEST['action']) && 'zm_clone_post_as_draft' == $_REQUEST['action'] ) ) ) {
wp_die('No post to clone has been supplied!');
}
// Nonce 验证
if ( !isset( $_GET['clone_nonce'] ) || !wp_verify_nonce( $_GET['clone_nonce'], basename( __FILE__ ) ) )
return;
// 获取原文章ID
$post_id = (isset($_GET['post']) ? absint( $_GET['post'] ) : absint( $_POST['post'] ) );
// 所有文章数据
$post = get_post( $post_id );
// 如果不希望当前用户作为新文章作者,将下两行替换为$new_post_author = $post->post_author;
$current_user = wp_get_current_user();
$new_post_author = $current_user->ID;
// 如果发布数据存在,则创建发布克隆
if (isset( $post ) && $post != null) {
// 创建新文章数组
$args = array(
'comment_status' => $post->comment_status,
'ping_status' => $post->ping_status,
'post_author' => $new_post_author,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_name' => $post->post_name,
'post_parent' => $post->post_parent,
'post_password' => $post->post_password,
'post_status' => 'draft',
'post_title' => $post->post_title,
'post_type' => $post->post_type,
'to_ping' => $post->to_ping,
'menu_order' => $post->menu_order
);
// 通过wp_insert_post() 函数添加文章
$new_post_id = wp_insert_post( $args );
// 将新的文章设置为草稿
$taxonomies = get_object_taxonomies($post->post_type); // 返回文章类型的分类数组,例如:array("category", "post_tag");
foreach ($taxonomies as $taxonomy) {
$post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'slugs'));
wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);
}
// 查询复制所有文章信息 post meta
$post_meta_infos = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id");
if (count($post_meta_infos)!=0) {
$sql_query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) ";
foreach ($post_meta_infos as $meta_info) {
$meta_key = $meta_info->meta_key;
if( $meta_key == '_wp_old_slug' ) continue;
$meta_value = addslashes($meta_info->meta_value);
$sql_query_sel[]= "SELECT $new_post_id, '$meta_key', '$meta_value'";
}
$sql_query.= implode(" UNION ALL ", $sql_query_sel);
$wpdb->query($sql_query);
}
wp_redirect( admin_url( 'edit.php?post_type='.$post->post_type ) );
exit;
} else {
wp_die('Post creation failed, could not find original post: ' . $post_id);
}
}
add_action( 'admin_action_zm_clone_post_as_draft', 'zm_clone_post_as_draft' );
// 复制文章并添加到列表
function zm_clone_post_link( $actions, $post ) {
if (current_user_can('edit_posts')) {
$actions['clone'] = '<a href="' . wp_nonce_url('admin.php?action=zm_clone_post_as_draft&post=' . $post->ID, basename(__FILE__), 'clone_nonce' ) . '" title="Clone this '.$post->post_type.'" rel="permalink">复制</a>';
}
return $actions;
}
add_filter( 'post_row_actions', 'zm_clone_post_link', 10, 2 );
add_filter('page_row_actions', 'zm_clone_post_link', 10, 2);
声明:本站所有软件资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。
