Wordpress钩子函数
# 图片类 hook
# jpeg_quality
修改图片上传后压缩质量(或关闭)
# 修改压缩质量代码
add_filter('jpeg_quality', function($arg){return 90;});
# 关闭图片上传后压缩
add_filter('jpeg_quality', function($arg){return 100;});
1
2
3
4
5
6
2
3
4
5
6
# big_image_size_threshold
关闭图片限制2560 pixels
add_filter( 'big_image_size_threshold', '__return_false' );
1
# upload_dir
将上传图片的目录从 uploads/年/月 -> uploads/年/月/日
function custom_upload_dir($dirs) {
$dirs['subdir'] = '/'.date('Y') . '/' . date('m') . '/' . date('d');
$dirs['path'] = $dirs['basedir'] . $dirs['subdir'];
$dirs['url'] = $dirs['baseurl'] . $dirs['subdir'];
return $dirs;
}
add_filter('upload_dir', 'custom_upload_dir');
1
2
3
4
5
6
7
2
3
4
5
6
7
function custom_upload_dir($dirs) {
// 获取当前日期和时间的各个部分
$year = date('Y');
$month = date('m');
$day = date('d');
$hour = date('H');
$minute = date('i');
// 构建子目录路径,格式为 /年/月/日_小时_分钟
$dirs['subdir'] = '/' . $year . '/' . $month . '/' . $day . '_' . $hour . '_' . $minute;
// 构建完整的物理路径
$dirs['path'] = $dirs['basedir'] . $dirs['subdir'];
// 构建完整的URL路径
$dirs['url'] = $dirs['baseurl'] . $dirs['subdir'];
// 检查目录是否存在,如果不存在则创建
if (!file_exists($dirs['path'])) {
wp_mkdir_p($dirs['path']);
}
return $dirs;
}
add_filter('upload_dir', 'custom_upload_dir');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 产品类 hook
# wc_product_sku_enabled
商品是否公开显示barcode
# Instructions
/**
* 隐藏商品barcode
*/
#add_filter( 'wc_product_sku_enabled', '__return_false' );
function sv_remove_product_page_skus( $enabled ) {
if ( ! is_admin() && is_product() ) {
return false;
}
return $enabled;
}
add_filter( 'wc_product_sku_enabled', 'sv_remove_product_page_skus' );
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# per_get_posts
修改每页显示产品数量
function custom_pre_get_posts( $query ) {
if ( ! is_admin() && $query->is_main_query() && ( is_shop() || is_product_category() || is_product_tag() ) ) {
// 设置每页显示的产品数量
$query->set( 'posts_per_page', 12 );
}
}
add_action( 'pre_get_posts', 'custom_pre_get_posts' );
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 订单类 hook
# 自定义地址 states
# Instructions
/**
* Add or modify States
*/
add_filter( 'woocommerce_states', 'custom_woocommerce_states' );
function custom_woocommerce_states( $states ) {
$states['NZ'] = array(
'AK' => 'Auckland',
'SL' => 'Southland',
'NL' => 'Northland'
);
return $states;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 强制订单字段必填
# instructions
add_filter( 'woocommerce_default_address_fields' , 'make_state_field_required', 90, 1 );
function make_state_field_required( $address_fields ) {
$address_fields['state']['required'] = true;
return $address_fields;
}
1
2
3
4
5
2
3
4
5
# API类 hook
# 限制API batch数量
# instructions
function wpse_rest_batch_items_limit( $limit ) {
$limit = 500;
return $limit;
}
add_filter( 'woocommerce_rest_batch_items_limit', 'wpse_rest_batch_items_limit' );
1
2
3
4
5
6
2
3
4
5
6
上次更新: 2024/06/02, 15:25:05