WP主题函数常用整理

wp-config

wp-config.php

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
//禁止更新

define('AUTOMATIC_UPDATER_DISABLED', true);

// SSL

$_SERVER['HTTPS'] = 'on';
define('FORCE_SSL_LOGIN', true);
define('FORCE_SSL_ADMIN', true);
// 禁止编辑主题和升级安装
define('DISALLOW_FILE_EDIT', true);
define('DISALLOW_FILE_MODS', true);

// 版本数
define( 'WP_POST_REVISIONS', 5 );
// 回收站有效期
define( 'EMPTY_TRASH_DAYS', 7 );

//屏蔽所有错误
ini_set("display_errors","Off");
ini_set("error_reporting", E_ALL );
define("WP_DEBUG", false);
define("WP_DEBUG_DISPLAY", false);


functions文件中

1
2
3
4
5
6
7
add_filter('pre_site_transient_update_core',    function($a){return null;}); // 关闭核心提示
add_filter('pre_site_transient_update_plugins', function($a){return null;}); // 关闭插件提示
add_filter('pre_site_transient_update_themes', function($a){return null;}); // 关闭主题提示
remove_action('admin_init', '_maybe_update_core'); // 禁止 WordPress 检查更新
remove_action('admin_init', '_maybe_update_plugins'); // 禁止 WordPress 更新插件
remove_action('admin_init', '_maybe_update_themes'); // 禁止 WordPress 更新主题

移除更新系统邮件通知

1
2
add_filter( 'auto_core_update_send_email', '__return_false' );

样式

1
2
3
4
5
6

function admin_lettering(){
echo'<link rel="stylesheet" style="text/css" href="'.get_stylesheet_directory_uri().'/bac-kui.css">';
}
add_action('admin_head', 'admin_lettering');

将the_content()放到短代码中

1
2
3
4
5
6
7
function custom_content(){

$content = apply_filters( 'the_content', get_the_content(), get_the_ID() );
return $content;
}

add_shortcode( 'custom_contents', 'custom_content' );

隐藏菜单以及插件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
add_filter( 'all_plugins', 'hide_plugins');
function hide_plugins($plugins)
{
// 隐藏 你好,多莉 插件
if(is_plugin_active('unlimited-elements-for-elementor-premium/unlimited-elements-pro.php')) {
unset( $plugins['unlimited-elements-for-elementor-premium/unlimited-elements-pro.php'] );
}
// 隐藏 post series插件
if(is_plugin_active('advanced-custom-fields-pro/acf.php')) {
unset( $plugins['advanced-custom-fields-pro/acf.php'] );
}
if(is_plugin_active('jet-elements/jet-elements.php')) {
unset( $plugins['jet-elements/jet-elements.php'] );
}
return $plugins;
}

add_action( 'admin_menu', function(){
remove_menu_page( 'jet-dashboard' );
remove_menu_page( 'edit.php?post_type=acf-field-group' ); //页面
remove_menu_page( 'unlimitedelements' ); //页面

},9001,1);

短代码-自动截取简介

1
2
3
4
5
6
7
8
9
10
11
12

function auto_excerpt($atts){
$content = apply_filters( 'the_content', get_the_content(), get_the_ID() );
$atts = shortcode_atts(array('num' => '200'),$atts);
if(has_excerpt()){ $exc = get_the_excerpt(); } else { $exc = mb_strimwidth(strip_tags($content),0,$atts['num'],'...'); }

return $exc;
}

add_shortcode('excerpts', 'auto_excerpt');


[excerpts num=200]

不写有默认值

面包屑导航函数

自定义文章自定义分类

分类页面包屑导航

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

function be_taxonomy_breadcrumb() {
// 定义分隔符
$separator = ' &#62; ';

// 获取当前术语
$term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
$type_name = get_post_type();
$post_type_labels = get_post_type_object($type_name)->labels->name;

// 输出面包屑开头
echo '<div class="breadcrumb"><i class="fa fa-home"></i> <a href="' . esc_url(get_home_url()) . '">Home</a>' . esc_html($separator);
echo '<a href="' . esc_url(get_post_type_archive_link($type_name)) . '">' . esc_html($post_type_labels) . '</a>' . esc_html($separator);

// 检查 $term 是否有效
if ($term && !is_wp_error($term)) {
$taxonomy_name = $term->taxonomy;

// 创建所有父术语的列表
$parent = $term->parent;
$parents = [];
while ($parent) {
$parents[] = $parent;
$new_parent = get_term_by('id', $parent, get_query_var('taxonomy'));
$parent = $new_parent && !is_wp_error($new_parent) ? $new_parent->parent : 0;
}

// 如果有父术语,反转数组并输出
if (!empty($parents)) {
$parents = array_reverse($parents);
foreach ($parents as $parent) {
$item = get_term_by('id', $parent, get_query_var('taxonomy'));
if ($item && !is_wp_error($item)) {
$url = get_bloginfo('url') . '/' . $item->taxonomy . '/' . $item->slug;
echo '<a href="' . esc_url($url) . '">' . esc_html($item->name) . '</a>' . esc_html($separator);
}
}
}

// 输出当前术语
echo '<a href="' . esc_url(get_term_link($term->term_id, $taxonomy_name)) . '">' . esc_html($term->name) . '</a>';
}

echo '</div>';
}

add_shortcode('be_taxonomy_breadcrumbs', 'be_taxonomy_breadcrumb');


详情页导航

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

function single_breadcrumbs() {
$separator = ' / ';

$post_id = get_the_ID();
$type_name = get_post_type($post_id);

$post_type_obj = get_post_type_object($type_name);
if (!$post_type_obj) {
return; // 如果文章类型无效,直接返回
}
$post_type_labels = $post_type_obj->labels->name;

// 获取分类法(确保至少有一个分类法)
$taxonomies = get_object_taxonomies($type_name);
$taxonomy = !empty($taxonomies[1]) ? $taxonomies[1] : (!empty($taxonomies[0]) ? $taxonomies[0] : '');

if (empty($taxonomy)) {
return;
}

$terms = get_the_terms($post_id, $taxonomy);
// 输出面包屑
echo '<div class="breadcrumb"><i class="fa fa-home"></i> <a href="' . esc_url(get_home_url()) . '">Home</a>' . esc_html($separator);
echo '<a href="' . esc_url(get_post_type_archive_link($type_name)) . '">' . esc_html($post_type_labels) . '</a>' . esc_html($separator);
// 检查术语是否有效
if ($terms && !is_wp_error($terms) && !empty($terms)) {
$term = $terms[0]; // 取第一个术语
$parent_id = $term->parent;

// 如果存在父术语,输出父术语
if ($parent_id) {
$parent_term = get_term($parent_id, $taxonomy);
if ($parent_term && !is_wp_error($parent_term)) {
echo '<a href="' . esc_url(get_term_link($parent_id, $taxonomy)) . '">' . esc_html($parent_term->name) . '</a>' . esc_html($separator);
}
}

// 输出当前术语
echo '<a href="' . esc_url(get_term_link($term->term_id, $taxonomy)) . '">' . esc_html($term->name) . '</a>';
}

echo '</div>';
}

add_shortcode('single_breadcrumb', 'single_breadcrumbs');


面包屑导航修改版

可兼容自定义类别

2022.07.01 修正 自定义字段中显示name 变为label

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

function get_hansel_and_gretel_breadcrumbs()
{
// Set variables for later use
// $here_text = __( '<i class="fa fa-home"></i>' );
$here_text = __( '' );
$home_link = home_url('/');
// $home_text = __( 'Home' );
$home_text = '首页';
$link_before = '<span typeof="v:Breadcrumb">';
$link_after = '</span>';
$link_attr = ' rel="v:url" property="v:title"';
$link = $link_before . '<a' . $link_attr . ' href="%1$s">%2$s</a>' . $link_after;
$delimiter = ' &raquo; '; // Delimiter between crumbs
$before = '<span class="current">'; // Tag before the current crumb
$after = '</span>'; // Tag after the current crumb
$page_addon = ''; // Adds the page number if the query is paged
$breadcrumb_trail = '';
$category_links = '';

/**
* Set our own $wp_the_query variable. Do not use the global variable version due to
* reliability
*/
$wp_the_query = $GLOBALS['wp_the_query'];
$queried_object = $wp_the_query->get_queried_object();

// Handle single post requests which includes single pages, posts and attatchments
if ( is_singular() )
{
/**
* Set our own $post variable. Do not use the global variable version due to
* reliability. We will set $post_object variable to $GLOBALS['wp_the_query']
*/
$post_object = sanitize_post( $queried_object );

// Set variables
$title = apply_filters( 'the_title', $post_object->post_title );
$parent = $post_object->post_parent;
$post_type = $post_object->post_type;
$post_id = $post_object->ID;
$post_link = $before . $title . $after;
$parent_string = '';
$post_type_link = '';

if ( 'post' === $post_type )
{
// Get the post categories
$categories = get_the_category( $post_id );
if ( $categories ) {
// Lets grab the first category
$category = $categories[0];

$category_links = get_category_parents( $category, true, $delimiter );
$category_links = str_replace( '<a', $link_before . '<a' . $link_attr, $category_links );
$category_links = str_replace( '</a>', '</a>' . $link_after, $category_links );
}
}

if ( !in_array( $post_type, ['post', 'page', 'attachment'] ) )
{
$post_type_object = get_post_type_object( $post_type );
$archive_link = esc_url( get_post_type_archive_link( $post_type ) );

$post_type_link = sprintf( $link, $archive_link, $post_type_object->label );

}

// Get post parents if $parent !== 0
if ( 0 !== $parent )
{
$parent_links = [];
while ( $parent ) {
$post_parent = get_post( $parent );

$parent_links[] = sprintf( $link, esc_url( get_permalink( $post_parent->ID ) ), get_the_title( $post_parent->ID ) );

$parent = $post_parent->post_parent;
}

$parent_links = array_reverse( $parent_links );

$parent_string = implode( $delimiter, $parent_links );
}

// Lets build the breadcrumb trail
if ( $parent_string ) {
$breadcrumb_trail = $parent_string . $delimiter . $post_link;
} else {
$breadcrumb_trail = $post_link;
}

if ( $post_type_link )

$breadcrumb_trail = $post_type_link . $delimiter . $breadcrumb_trail;

if ( $category_links )
$breadcrumb_trail = $category_links . $breadcrumb_trail;
}

// Handle archives which includes category-, tag-, taxonomy-, date-, custom post type archives and author archives
if( is_archive() )
{
if ( is_category()
|| is_tag()
|| is_tax()
) {
// Set the variables for this section
$term_object = get_term( $queried_object );
$taxonomy = $term_object->taxonomy;
$term_id = $term_object->term_id;
$term_name = $term_object->name;
$term_parent = $term_object->parent;
$taxonomy_object = get_taxonomy( $taxonomy );
// $current_term_link = $before . $taxonomy_object->labels->singular_name . ': ' . $term_name . $after;
$current_term_link = $before . $term_name . $after;
$parent_term_string = '';

if ( 0 !== $term_parent )
{
// Get all the current term ancestors
$parent_term_links = [];
while ( $term_parent ) {
$term = get_term( $term_parent, $taxonomy );

$parent_term_links[] = sprintf( $link, esc_url( get_term_link( $term ) ), $term->name );

$term_parent = $term->parent;
}

$parent_term_links = array_reverse( $parent_term_links );
$parent_term_string = implode( $delimiter, $parent_term_links );
}

if ( $parent_term_string ) {
$breadcrumb_trail = $parent_term_string . $delimiter . $current_term_link;
} else {
$breadcrumb_trail = $current_term_link;
}

} elseif ( is_author() ) {

$breadcrumb_trail = __( 'Author archive for ') . $before . $queried_object->data->display_name . $after;

} elseif ( is_date() ) {
// Set default variables
$year = $wp_the_query->query_vars['year'];
$monthnum = $wp_the_query->query_vars['monthnum'];
$day = $wp_the_query->query_vars['day'];

// Get the month name if $monthnum has a value
if ( $monthnum ) {
$date_time = DateTime::createFromFormat( '!m', $monthnum );
$month_name = $date_time->format( 'F' );
}

if ( is_year() ) {

$breadcrumb_trail = $before . $year . $after;

} elseif( is_month() ) {

$year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );

$breadcrumb_trail = $year_link . $delimiter . $before . $month_name . $after;

} elseif( is_day() ) {

$year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );
$month_link = sprintf( $link, esc_url( get_month_link( $year, $monthnum ) ), $month_name );

$breadcrumb_trail = $year_link . $delimiter . $month_link . $delimiter . $before . $day . $after;
}

} elseif ( is_post_type_archive() ) {

$post_type = $wp_the_query->query_vars['post_type'];
$post_type_object = get_post_type_object( $post_type );

$breadcrumb_trail = $before . $post_type_object->label . $after;

}
}

// Handle the search page
if ( is_search() ) {
$breadcrumb_trail = __( 'Search query for: ' ) . $before . get_search_query() . $after;
}

// Handle 404's
if ( is_404() ) {
$breadcrumb_trail = $before . __( 'Error 404' ) . $after;
}

// Handle paged pages
if ( is_paged() ) {
$current_page = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : get_query_var( 'page' );
$page_addon = $before . sprintf( __( ' ( Page %s )' ), number_format_i18n( $current_page ) ) . $after;
}

$breadcrumb_output_link = '';
$breadcrumb_output_link .= '<div class="breadcrumb">';
if ( is_home()
|| is_front_page()
) {
// Do not show breadcrumbs on page one of home and frontpage
if ( is_paged() ) {
$breadcrumb_output_link .= $here_text ;
$breadcrumb_output_link .= '<a href="' . $home_link . '">' . $home_text . '</a>';
$breadcrumb_output_link .= $page_addon;
}
} else {
// $breadcrumb_output_link .= $here_text . $delimiter;
$breadcrumb_output_link .= $here_text ;
$breadcrumb_output_link .= '<a href="' . $home_link . '" rel="v:url" property="v:title">' . $home_text . '</a>';
$breadcrumb_output_link .= $delimiter;
$breadcrumb_output_link .= $breadcrumb_trail;
$breadcrumb_output_link .= $page_addon;
}
$breadcrumb_output_link .= '</div><!-- .breadcrumbs -->';

return $breadcrumb_output_link;

}

add_shortcode('breadcrumbs', 'get_hansel_and_gretel_breadcrumbs');

小部件Twig 模板引擎获取获取文章中第一张图为缩略图

Twig是无法实现的,通过PHP函数才能实现
PHP函数放在function中

1
2
3
4
5
6
7
8
9
10
11
function catch_the_image( $post_content ) {
// global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches);
$first_img = $matches [1] [0];

echo $first_img;
}

利用wordpress钩子函数

1
add_action('auto_img','catch_the_image');

图片src,在post list循环中使用

1
{{do_action('auto_img', item.post_list.content|wpautop|raw) }}

图片URL引号中的内容正则表达式

1
$output = preg_match_all("/(.+\.(jpg|gif|bmp|bnp|png))/", $str, $matches);

add_filter获取方式,可传参

1
2
3
4
5
6
7
8
9
10
11
function f_catch_the_image( $post_content ) {
// global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches);
$first_img = $matches [1] [0];
return $first_img;
}
add_filter( 'get_img', 'f_catch_the_image', 10, 3 );

接收结果

1
2
{% set img_content = apply_filters('get_img', item.post_list.content|wpautop|raw) %}

完美的缩略图获取判断

1
2
3
4
5
6
7
8
9
10
{% if item.post_list.image is empty %}
{% if img_content is empty %}
<img src="{{uc_assets_url}}/{{ random(1, 5) }}.jpg">
{% else %}
<img src="{{do_action('auto_img', item.post_list.content|wpautop|raw) }}">
{% endif %}
{% else %}
<img src="{{item.post_list.image}}" {{item.post_list.image_attributes|raw}}>
{% endif %}

WordPress中PHP配置的调整

更新wp-config.php文件

1
2
3
4
5
@ini_set('upload_max_filesize','128M');
@ini_set('post_max_size','128M');
@ini_set('memory_limit','256M');
@ini_set('max_execution_time','300');
@ini_set('max_input_time','300');

部分国外主机是更新.htaccess文件

1
2
3
4
5
php_value upload_max_filesize 128M
php_value post_max_size 128M
php_value memory_limit 256M
php_value max_execution_time 300
php_value max_input_time 300

子主题路径

url路径

1
2
<?php echo get_stylesheet_directory_uri();?>

绝对路径

1
<?php echo get_stylesheet_directory();?>

指定子分类 短代码

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
26

function catelist($atts){

$atts = shortcode_atts(array( 'id' => '0', ), $atts );

$args = array('child_of' => $atts['id'], 'hide_empty' => 0);
$categories = get_categories($args);

if ($categories) {
$output = "<ul class='list-cate'>";

foreach ($categories as $category) {
$output .= sprintf(
"<li class='cat-%s'><a href="%s" title='%s'>%s</a></li>",
$category->slug,
get_category_link($category->term_id),
sprintf(__('View all posts in %s'), $category->name),
$category->name
);
}

$output .= "</ul>";

}
return $output;
}

输出 [cate id=1]

国外在线聊天常用链接

1
2
3
4
5
6
7
8
<!-- WhatsApp -->
<a href="https://api.whatsapp.com/send?phone=+17638166923&text=Hello">WhatsApp</a>
<!-- 手机端 -->
<a href="whatsapp://send?phone=+17638166923&text=Hello">WhatsApp</a>

<!-- Skype -->
skype:17638166923?call

transposh自动翻译

1
2
3
4
5
6
7
8
[tp widget="flags/tpw_flags_css.php"]
[tp widget="flags/tpw_flags.php"]
[tp widget="default/tpw_default.php"]
[tp widget="dropdown/tpw_image_dropdown.php"]
[tp widget="flagslist /tpw_list_with_flags_css.php"]
[tp widget="flagslist /tpw_list_with_flags.php"]
[tp widget="select2 /tpw_select2.php"]

php中输出短代码

1
2
3

<?php echo do_shortcode('[tp widget="default/tpw_default.php"]'); ?>

文章浏览次数

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
function gt_get_post_view() {
$count = get_post_meta( get_the_ID(), 'post_views_count', true );
return "$count views";
}
function gt_set_post_view() {
$key = 'post_views_count';
$post_id = get_the_ID();
$count = (int) get_post_meta( $post_id, $key, true );
$count++;
update_post_meta( $post_id, $key, $count );
}
function gt_posts_column_views( $columns ) {
$columns['post_views'] = 'Views';
return $columns;
}
function gt_posts_custom_column_views( $column ) {
if ( $column === 'post_views') {
echo gt_get_post_view();
}
}
add_filter( 'manage_posts_columns', 'gt_posts_column_views' );
add_action( 'manage_posts_custom_column', 'gt_posts_custom_column_views' );


add_shortcode( 'the_post_views', 'gt_get_post_view' );
1
2
3
4
5
6
7
// 循环中使用
<?php gt_set_post_view(); ?>

// 单页中使用
<?php gt_get_post_view(); ?>


配合短代码中输出

1
2
[the_post_views]

自定义分类 显示代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 在详情页
function custom_category(){
global $post;
$terms = wp_get_post_terms( $post->ID, 'products',array("fields" => "names"));
echo $terms[0]; #displays the output
}
add_shortcode( 'custom_categories', 'custom_category' );

// 在分类页
function cate_page_custom_category(){
$terms = get_queried_object();
echo $terms->label;
}

add_shortcode( 'cate_page_custom_categories', 'cate_page_custom_category' );


参数拓展

1
2
3
4
5
6
7
8
9
10
11
12
13
14

//Returns All Term Items for "my_taxonomy"
$term_list = wp_get_post_terms($post->ID, 'my_taxonomy', array("fields" => "all"));
print_r($term_list);
//Returns Array of Term Names for "my_taxonomy"
$term_list = wp_get_post_terms($post->ID, 'my_taxonomy', array("fields" => "names"));
print_r($term_list);
//Returns Array of Term ID's for "my_taxonomy"
$term_list = wp_get_post_terms($post->ID, 'my_taxonomy', array("fields" => "ids"));
print_r($term_list);
//Echo a single value - $term_list is an array of objects. You must select one of the // array entries before you can reference its properties (fields).
$term_list = wp_get_post_terms($post->ID, 'my_taxonomy', array("fields" => "all"));
echo $term_list[0]->description ;

手机端判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

function get_is_mobile(){
//get_ 传递
$var = wp_is_mobile();//wordpress自带函数
return $var;
}


// 传递
{% set is_mobile = getByPHPFunction('get_is_mobile') %}

//判断
{% if is_mobile == true %}

{% endif %}

WooCommerce 隐藏全部产品价格

1
2
3
4
5
add_filter( 'woocommerce_get_price_html', 'react2wp_woocommerce_hide_product_price' );
function react2wp_woocommerce_hide_product_price( $price ) {
return '';
}

删除添加到购物车按钮并禁用购买功能

1
2
3
4
add_filter ( 'woocommerce_is_purchasable' , '__return_false' ); // 禁用购买功能并从普通产品中删除添加到购物车按钮
remove_action ( 'woocommerce_single_variation' , 'woocommerce_single_variation' , 10 ); // 从变化中移除价格
remove_action ( 'woocommerce_single_variation' , 'woocommerce_single_variation_add_to_cart_button' , 20 ); // 从变化中删除添加到购物车按钮

从商店页面/存档隐藏添加到购物车按钮,同时保留购买功能

1
2
3
4
5
6
7
8
function react2wp_is_shop_remove_add_to_cart_button() {
if ( is_shop() ) {
add_filter( 'woocommerce_is_purchasable', '__return_false' );
}
}

add_action( 'wp_head', 'react2wp_is_shop_remove_add_to_cart_button' );

从类别页面删除添加到购物车按钮,同时保留购买功能

1
2
3
4
5
6
7
8
9

function react2wp_is_shop_remove_add_to_cart_button() {
if ( is_product_category() ) {
add_filter( 'woocommerce_is_purchasable', '__return_false' );
}
}

add_action( 'wp_head', 'react2wp_is_shop_remove_add_to_cart_button' );

从单个产品页面删除添加到购物车按钮,同时保留购买功能

1
2
3
4
5
6
7
8
function react2wp_is_shop_remove_add_to_cart_button() {
if ( is_product() ) {
add_filter( 'woocommerce_is_purchasable', '__return_false' );
}
}

add_action( 'wp_head', 'react2wp_is_shop_remove_add_to_cart_button' );

直接购买(多sku有效)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

/* Dynamic Button for Simple & Variable Product *//**
* Main Functions
*/function sbw_wc_add_buy_now_button_single()
{
global $product;
printf( '<button id="sbw_wc-adding-button" type="submit" name="sbw-wc-buy-now" value="%d" class="single_add_to_cart_button buy_now_button button alt">%s</button>', $product->get_ID(), esc_html__( 'Buy Now', 'sbw-wc' ) );
}add_action( 'woocommerce_after_add_to_cart_button', 'sbw_wc_add_buy_now_button_single' );/*** Handle for click on buy now ***/
function sbw_wc_handle_buy_now()
{
if ( !isset( $_REQUEST['sbw-wc-buy-now'] ) )
{
return false;
}WC()->cart->empty_cart();$product_id = absint( $_REQUEST['sbw-wc-buy-now'] );
$quantity = absint( $_REQUEST['quantity'] );if ( isset( $_REQUEST['variation_id'] ) ) {$variation_id = absint( $_REQUEST['variation_id'] );
WC()->cart->add_to_cart( $product_id, 1, $variation_id );}else{
WC()->cart->add_to_cart( $product_id, $quantity );
}wp_safe_redirect( wc_get_checkout_url() );
exit;
}add_action( 'wp_loaded', 'sbw_wc_handle_buy_now' );

隐藏产品评论

1
2
3
4
5
6
7
8
9
/**
* Disable reviews.
*/
function iconic_disable_reviews() {
remove_post_type_support( 'product', 'comments' );
}

add_action( 'init', 'iconic_disable_reviews' );

购物车增加件数自动刷新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

add_action( 'wp_footer', 'bbloomer_cart_refresh_update_qty' );

function bbloomer_cart_refresh_update_qty() {
if (is_cart()) {
?>
<script type="text/javascript">
jQuery('div.woocommerce').on('change', 'input.qty', function(){
setTimeout(function() {
jQuery('[name="update_cart"]').trigger('click');
}, 100 );
});
</script>
<?php
}
}

移除子菜单

原链接为 /wp-admin/edit.php?post_type=coforpaypal_order&page=checkout-for-paypal-addons

1
2
3

remove_submenu_page('edit.php?post_type=coforpaypal_order','checkout-for-paypal-addons');

自定义wooc按钮

自定buy按钮

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

add_filter( 'woocommerce_product_add_to_cart_text' , 'custom_select_options_text' );
function custom_select_options_text() {
global $product;
$product_type = $product->product_type;
switch ( $product_type ) {
case 'subscription':
return __( 'Options', 'woocommerce' ); /*change 'Options' for Simple Subscriptions */
case 'variable-subscription':
return __( 'Options', 'woocommerce' ); /*change 'Options' for Variable Subscriptions */
case 'variable':
return __( 'Options', 'woocommerce' ); /*change 'Options' for Variable Products */
case 'simple':
return __( 'Add to Cart', 'woocommerce' ); /*change 'Add to Cart' for Simple Products */
break;
}
}

自定义类别动态链接

1
2
3
4
5
6
7

function custom_product_links(){
$links = '<a class="menu-link" href="'.get_post_type_archive_link('product').'">Products</ a>';
return $links;
}
add_shortcode('custom_product_link', 'custom_product_links');

add cart 后面加按钮

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function add_content_after_addtocart() {

// get the current post/product ID
$current_product_id = get_the_ID();

// get the product based on the ID
$product = wc_get_product( $current_product_id );

// get the "Checkout Page" URL
$checkout_url = WC()->cart->get_checkout_url();

// run only on simple products
if( $product->is_type( 'simple' ) ){
echo '< a href="'.$checkout_url.'?add-to-cart='.$current_product_id.'" class="single_add_to_cart_button button alt">Checkout</ a>';
}
}
add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart' );

最简单的实现浏览数 Post View

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 加到functions.php

// THIS FUNCTION RETURS NUMBER OF VIEWS FOR A POST
function getPostViewCount(){
$postID = get_the_ID();
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '1');
return 1;
}
if(intval($count) > 1000){
return number_format($count/1000,1).'K';
}elseif(intval($count) > 1000000){
return number_format($count/1000000,1).'M';
}else{
return $count;
}
}

// THIS FUNCTION COUNTS POST VIEWS
function setPostViewCount() {
$postID = get_the_ID();
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
return $count;
}

// single中使用
setPostViews();
//category中使用
getPostViewCount()

小部件Twig 列表模板中使用

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
26
27
function getPostViewCounts($postsid){
$postID = $postsid;
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '1');
return 1;
}
if(intval($count) > 1000){
return number_format($count/1000,1).'K';
}elseif(intval($count) > 1000000){
return number_format($count/1000000,1).'M';
}else{
return $count;
}
}

add_filter( 'getPostViewCount', 'getPostViewCounts', 10, 3 );

// 小部件Twig获取

{% set postlike = apply_filters('postlike', item.post_list.id) %}

{% set PostViewCount = apply_filters('getPostViewCount', item.post_list.id) %}

{{postlike|raw}}

点赞小红心

完整代码下载
四个步骤
1、将 CSS 添加到主题的主样式表中。
2、将 文件添加到主题的 js 文件夹。并向其中添加 simple-likes-public.js
3、将 post-like.php 的内容添加到主题的 functions.php 文件中。
4、循环中使用 echo get_simple_likes_button( get_the_ID() );
通过确保按钮函数中的第二个参数设置为“1”,将按钮添加到主题中的任何评论 — echo get_simple_likes_button( get_comment_ID(), 1 );
简码 [jmliker]

1
2
3
4
5

require_once(get_stylesheet_directory().'/post-like.php');

<link rel='stylesheet' href="<?php echo get_stylesheet_directory_uri();?>/css/simple-likes-public.css" >

-注意:如果是子主题中,post-like.php中,第29行要修改为 get_stylesheet_directory_uri()-

如果访问wp-login.php则指定跳转

1
2
3
4
5
6
7
8
add_action('init','fanly_custom_login');
function fanly_custom_login(){
global $pagenow;
if( 'wp-login.php' == $pagenow ) {
wp_redirect(get_permalink('11'));//跳转到首页
die();
}
}

加个菜单

1
2
3
4
5
6
7
add_action('admin_menu', 'add_custom_menu_link');
function add_custom_menu_link()
{
$links= get_home_url()."/wp-admin/admin.php?page=e-form-submissions#/";
add_menu_page('留言表单', '留言表单', 'read', $links, '', 'dashicons-text', 6);
}

给table 通过JS 加个div

1
2
3
4
5
6
7
8
9
10
11
add_action( 'wp_footer', 'add_js_to_wp_footer' );
function add_js_to_wp_footer(){ ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$(function() {
$('table').wrap('<div class="table-responsive"></div>');
})
})
</script>
<?php }

query acf自定义字段输出

1
2
3
4
5
6
7
8
9
$args = array('showposts' => 8, 'post_type' => 'post',
'meta_query' => array('relation' => 'OR',
array('key' => 'special', 'value' => 'feature_products', 'compare' => 'LIKE')));
$the_query = new WP_Query($args);
if ($the_query->have_posts()) : while ($the_query->have_posts()) : $the_query->the_post();


//acf自定义字段 输出 post列表 acf 字段 special 值为feature Products 显示 这里部分书写存在有误

宝塔 数据库自动重启任务

1
2
3
4
5
6
7
8
9
pgrep -x mysqld &> /dev/null
if [ $? -ne 0 ]
then
echo "At time: `date` : Mysql is stop.">> /data/log/mysql_auto_start.log
/etc/init.d/mysqld start
else
echo "Mysql server is running."
fi

使用acf自定义字段替换用户默认avatar图

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
26
function replace_default_avatar($avatar, $id_or_email, $size, $default, $alt) {
// 获取用户ID
if (is_numeric($id_or_email)) {
$user_id = (int) $id_or_email;
} elseif (is_object($id_or_email)) {
if (!empty($id_or_email->user_id)) {
$user_id = (int) $id_or_email->user_id;
}
} else {
$user = get_user_by('email', $id_or_email);
$user_id = $user ? $user->ID : null;
}

// 如果用户ID存在,获取ACF自定义字段user_img
if ($user_id) {
$user_img = get_field('user_img', 'user_' . $user_id);
if ($user_img) {
// 替换默认头像
$avatar = '<img src="' . esc_url($user_img['url']) . '" alt="' . esc_attr($alt) . '" width="' . esc_attr($size) . '" height="' . esc_attr($size) . '" class="avatar avatar-' . esc_attr($size) . ' photo" />';
}
}

return $avatar;
}
add_filter('get_avatar', 'replace_default_avatar', 10, 5);

自定义文章类型single页面下相关产品

随机当前文章所属分类下的文章

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function single_relate_pro_list() {
// 获取当前文章的分类
$postcat = get_the_terms(get_the_ID(), 'products');

if (!empty($postcat) && !is_wp_error($postcat)) {
$args = array(
'post_type' => 'product',
'posts_per_page' => 4,
'orderby'=> 'rand',
'tax_query' => array(
array(
'taxonomy' => 'products',
'field' => 'term_id',
'terms' => $postcat[0]->term_id,

),
),
);

$output = "<ul class='relate'>";
$query = new WP_Query($args);

if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$output .= sprintf(
"<li><a href='%s'><img src='%s' alt='%s'><h3>%s</h3></a></li>",
get_the_permalink(),
get_the_post_thumbnail_url(),
get_the_title(),
get_the_title()
);
}
wp_reset_postdata();
} else {
$output .= "<li>No related products found</li>";
}

$output .= "</ul>";
} else {
$output = "<ul class='relate'><li>No related products found</li></ul>";
}

return $output;
}
add_shortcode('single_relate_pro_lists', 'single_relate_pro_list');

后台自定义分类管理列表增加列方法

自定义分类products 管理列表显示 通过acf增加的自定义字段cate_banner,同时显示在倒数第二个列
如图

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

function add_custom_taxonomy_column($columns,$taxonomy='products'){
if ($taxonomy === 'products') {
// 获取所有列的键,按顺序排列
$column_keys = array_keys($columns);
// 获取倒数第二个键
$last_second_key = end($column_keys);

$new_columns = [];
foreach ($column_keys as $key) {
if ($key === $last_second_key) {
$new_columns['cate_banner'] = '横幅大图';
}
$new_columns[$key] = $columns[$key];
}

return $new_columns;
}

return $columns;
}
add_filter( "manage_edit-products_columns", 'add_custom_taxonomy_column', 10,2);
// manage_edit-自定义分类名_columns
function custom_column_content( $value, $column_name, $tax_id ){


switch ( $column_name ) {

case 'cate_banner' :
$cate_banner = get_field('cate_banner', 'products_'.$tax_id );
if(isset($category_thumb)){
$thumb = $cate_banner["sizes"]["medium"];
}
if ($cate_banner)
//var_dump();
echo '<img src="'.esc_url($thumb).'">';
else
echo "—";
break;


}

}
add_action( "manage_products_custom_column", 'custom_column_content', 10, 3);
// manage_自定义分类名_custom_column

自定义文章类型product

注意 manage_自定义文章类型名_posts_columns
结合ACF实现推荐首页显示

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
add_filter( 'manage_product_posts_columns', 'set_custom_edit_book_columns' );
add_action( 'manage_product_posts_custom_column' , 'custom_book_column', 10, 2 );
function set_custom_edit_book_columns($columns) {
unset( $columns['author'] );

$columns['hot_index'] = __( '推荐', 'Sticky' );

return $columns;
}

function custom_book_column( $column, $post_id ) {
switch ( $column ) {

case 'hot_index' :
$hot_indexs = get_field('hot_index', $post_id );
if ($hot_indexs)
echo "<b style='color:#f00;'>已推荐</b>";
else
echo "否";
break;


}
}

自定义post type 去除URL中的slug

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
26
27
28
29
30
31
32
33
34
35
36
37



function km_remove_cpt_slug( $post_link, $post ) {
if ( 'product' === $post->post_type && 'publish' === $post->post_status ) {
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
if ( ! is_admin() ) {
$post_link.='.html';
}
}

return $post_link;
}
add_filter( 'post_type_link', 'km_remove_cpt_slug', 10, 2 );

/**
* Have WordPress match postname to any of our public post types (post, page, my-cpt-slug).
* All of our public post types can have /post-name/ as the slug, so they need to be unique across all posts.
* By default, WordPress only accounts for posts and pages where the slug is /post-name/.
*
* @param $query The current query.
*/
function km_add_cpt_post_names_to_main_query( $query ) {

if (
! $query->is_main_query()
|| ! isset( $query->query['page'] )
|| 2 !== count( $query->query )
|| empty( $query->query['name'] )
) {
return;
}

$query->set( 'post_type', array( 'product' ) );
}
add_action( 'pre_get_posts', 'km_add_cpt_post_names_to_main_query' );

Elementor 表单过滤违禁词

在Settings > Discussion > Comment设置违禁词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
add_action( 'elementor_pro/forms/validation', function($record, $ajax_handler) {
$disallowed_keys = get_option('disallowed_keys', '');
if (empty($disallowed_keys)) {
return; // 没有黑名单词,直接返回
}

$blackwords = array_filter(array_map('trim', explode("\n", $disallowed_keys)));
if (empty($blackwords)) {
return; // 没有有效黑名单词
}

$fields = $record->get_field([]);
foreach ($fields as $field) {
foreach ($blackwords as $blackword) {
$regex = '|' . preg_quote($blackword, '|') . '|i';
if (preg_match($regex, $field['value'])) {
$ajax_handler->add_error($field['id'], esc_html__('This field contains a restricted word.', 'elementor-pro'));
return;
}
}
}
}, 10, 2);

unlimited elementor插件配合wooc产品

配合function函数,自定义选择显示feature精选产品

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function getFeaturedProductIDs($arg = '') {
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_visibility',
'field' => 'slug',
'terms' => 'featured',
),
),
);

$query = new WP_Query($args);
$product_ids = wp_list_pluck($query->posts, 'ID');

// Convert integers to strings to match your example format
$product_ids = array_map('strval', $product_ids);

return $product_ids;
}