wordpress 函数_WordPress函数文件的32个极其有用的技巧
2022-07-29 10:13:20
183
{{single.collect_count}}

wordpress 函数

All WordPress themes come with a powerful functions.php file. This file acts as a plugin and allows you to do lots of cool things on your WordPress site. In this article, we will show you some of the most useful tricks for your WordPress functions file.

所有WordPress主题都带有功能强大的functions.php文件。 该文件充当插件,使您可以在WordPress网站上做很多有趣的事情。 在本文中,我们将向您展示WordPress函数文件的一些最有用的技巧。

Most useful tricks for WordPress functions file

WordPress中的功能文件是什么? (What is Functions File in WordPress?)

Functions file commonly known as functions.php file is a WordPress theme file. It comes with all free and premium WordPress themes.

功能文件通常称为functions.php文件,是WordPress主题文件。 它带有所有免费和高级WordPress主题

The purpose of this file is to allow theme developers to define theme features and functions. This file acts just like a WordPress plugin and can be used to add your own custom code snippets in WordPress.

该文件的目的是允许主题开发人员定义主题功能。 该文件的行为就像WordPress插件一样,可用于在WordPress中添加您自己的自定义代码段。

You would find many of these code snippets on websites like WPBeginner with instructions telling you to add this code in your theme’s functions.php file or a site-specific WordPress plugin.

您会在WPBeginner这样的网站上找到许多这些代码段,并附带指示,要求您将此代码添加到主题的functions.php文件或特定站点的WordPress插件中

Now you may be thinking what’s the difference between a site-specific WordPress plugin and functions.php file? Which one is better?

现在,您可能正在考虑特定于站点的WordPress插件和functions.php文件有什么区别? 哪一个更好?

While functions.php file is more convenient, a site-specific plugin is much better. Simply because it is independent of your WordPress theme and would work regardless of which theme you are using.

尽管functions.php文件更方便,但特定于站点的插件要好得多。 仅仅是因为它独立于您的WordPress主题,并且无论您使用哪个主题都可以使用。

On the other hand, a theme’s functions file will only work for that theme and if you switch the theme, then you will have to copy / paste your custom codes into the new theme.

另一方面,主题的功能文件仅适用于该主题,如果您切换该主题,则必须将自定义代码复制/粘贴到新主题中。

Having said that, here are some extremely useful tricks for the WordPress functions file.

话虽如此,这是WordPress函数文件的一些非常有用的技巧。

1.删​​除WordPress版本号 (1. Remove WordPress Version Number)

You should always use the latest version of WordPress. However, you may still want to remove the WordPress version number from your site. Simply add this code snippet to your functions file.

您应该始终使用最新版本的WordPress 。 但是,您可能仍想从站点中删除WordPress版本号。 只需将此代码段添加到您的功能文件中即可。

function wpb_remove_version() {return '';}add_filter('the_generator', 'wpb_remove_version');

For detailed instructions, see our guide on the right way to remove WordPress version number.

有关详细说明,请参阅有关删除WordPress版本号的正确方法的指南。

Want to white label your WordPress admin area? Adding a custom dashboard logo is the first step in the process.

想要给您的WordPress管理区域贴上白色标签? 添加自定义仪表板徽标是该过程的第一步。

First you’ll need to upload your custom logo to your theme’s images folder as custom-logo.png. Make sure your custom logo is 16×16 pixels in size.

首先,您需要将自定义徽标作为custom-logo.png上载到主题的图像文件夹中。 确保自定义徽标的尺寸为16×16像素。

After that you can add this code to your theme’s functions file.

之后,您可以将此代码添加到主题的功能文件中。

function wpb_custom_logo() {echo '<style type="text/css">#wpadminbar #wp-admin-bar-wp-logo > .ab-item .ab-icon:before {background-image: url(' . get_bloginfo('stylesheet_directory') . '/images/custom-logo.png) !important;background-position: 0 0;color:rgba(0, 0, 0, 0);}#wpadminbar #wp-admin-bar-wp-logo.hover > .ab-item .ab-icon {background-position: 0 0;}</style>';}//hook into the administrative header outputadd_action('wp_before_admin_bar_render', 'wpb_custom_logo');

For alternate methods and more details see our guide on how to add a custom dashboard logo in WordPress.

有关替代方法和更多详细信息,请参见有关如何在WordPress中添加自定义仪表板徽标的指南。

3.在WordPress管理面板中更改页脚 (3. Change the Footer in WordPress Admin Panel)

The footer in WordPress admin area shows the message ‘Thank you for creating with WordPress’. You can change it to anything you want by adding this code.

WordPress管理区域中的页脚显示消息“谢谢您使用WordPress创建”。 您可以通过添加以下代码将其更改为所需的任何内容。

function remove_footer_admin () {echo 'Fueled by <a href="http://www.wordpress.org" target="_blank">WordPress</a> | WordPress Tutorials: <a href="https://www.wpbeginner.com" target="_blank">WPBeginner</a></p>';}add_filter('admin_footer_text', 'remove_footer_admin');

Feel free to change the text and links that you want to add. Here is how it looks on our test site.

随时更改要添加的文本和链接。 这是我们测试站点上的外观。

Custom footer in WordPress admin area

4.在WordPress中添加自定义仪表板小部件 (4. Add Custom Dashboard Widgets in WordPress)

You probably have seen widgets that numerous plugins and themes add in the WordPress dashboard. As a theme developer, you can add one yourself by pasting the following code:

您可能已经看到WordPress仪表板中添加了许多插件和主题的小部件。 作为主题开发人员,您可以通过粘贴以下代码来添加自己:

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');function my_custom_dashboard_widgets() {global $wp_meta_boxes;wp_add_dashboard_widget('custom_help_widget', 'Theme Support', 'custom_dashboard_help');}function custom_dashboard_help() {echo '<p>Welcome to Custom Blog Theme! Need help? Contact the developer <a href="mailto:yourusername@gmail.com">here</a>. For WordPress Tutorials visit: <a href="https://www.wpbeginner.com" target="_blank">WPBeginner</a></p>';}

This is how it would look like:

它是这样的:

Custom dashboard widget in WordPress

For details, see our tutorial on how to add custom dashboard widgets in WordPress.

有关详细信息,请参阅有关如何在WordPress中添加自定义仪表板小部件的教程。

5.更改WordPress中的默认Gravatar (5. Change the Default Gravatar in WordPress)

Have you seen the default mystery man avatar on blogs? You can easily replace it with your own branded custom avatars. Simply upload the image you want to use as default avatar and then add this code to your functions file.

您是否在博客上看到默认的神秘人头像? 您可以轻松地用您自己的品牌自定义头像替换它。 只需上传您要用作默认头像的图像,然后将此代码添加到您的功能文件中即可。

add_filter( 'avatar_defaults', 'wpb_new_gravatar' );function wpb_new_gravatar ($avatar_defaults) {$myavatar = 'http://example.com/wp-content/uploads/2017/01/wpb-default-gravatar.png';$avatar_defaults[$myavatar] = "Default Gravatar";return $avatar_defaults;}

Now you can head over to Settings » Discussion page and select your default avatar.

Custom default gravatar

现在,您可以转到“设置”»“讨论”页面,然后选择默认头像。

For detailed instructions, see our guide on how to change the default gravatar in WordPress.

有关详细说明,请参见有关如何在WordPress中更改默认Gravatar的指南。

6. WordPress页脚中的动态版权日期 (6. Dynamic Copyright Date in WordPress Footer)

You can simply add copyright date by editing the footer template in your theme. However, it will not show when your site started and it will not automatically change next year.

您只需在主题中编辑页脚模板即可添加版权日期。 但是,它不会显示您的网站何时启动,并且明年不会自动更改。

You can use this code to add a dynamic copyright date in WordPress footer.

您可以使用此代码在WordPress页脚中添加动态版权日期。

function wpb_copyright() {global $wpdb;$copyright_dates = $wpdb->get_results("SELECTYEAR(min(post_date_gmt)) AS firstdate,YEAR(max(post_date_gmt)) AS lastdateFROM$wpdb->postsWHEREpost_status = 'publish'");$output = '';if($copyright_dates) {$copyright = "© " . $copyright_dates[0]->firstdate;if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {$copyright .= '-' . $copyright_dates[0]->lastdate;}$output = $copyright;}return $output;}

After adding this function, you’ll need to open your footer.php file and add the following code wherever you like to display the dynamic copyright date:

添加此功能后,您需要打开footer.php文件,并在想要显示动态版权日期的任何位置添加以下代码:

<?php echo wpb_copyright(); ?>

This function looks for the date of your first post, and the date of your last post. It then echos the years wherever you call the function.

此功能查找您的第一篇文章的日期和您的最后一篇文章的日期。 然后,无论您在何处调用函数,它都会回显年份。

For more details, see our guide on how to add dynamic copyright date in WordPress.

有关更多详细信息,请参见有关如何在WordPress中添加动态版权日期的指南。

7.在WordPress中随机更改背景颜色 (7. Randomly Change Background Color in WordPress)

Do you want to randomly change background color on your WordPress upon each visit and page reload? Here is how to easily do this.

您是否要在每次访问和重新加载页面时随机更改WordPress上的背景颜色? 这是轻松完成此操作的方法。

First you need to add this code to your theme’s functions file.

首先,您需要将此代码添加到主题的功能文件中。

function wpb_bg() { $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');$color ='#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];echo $color;}

Next, you’ll need to edit the header.php file in your theme. Locate the <body> tag and add replace it with this line:

接下来,您需要在主题中编辑header.php文件。 找到<body>标签,并添加以下行:

<body <?php body_class(); ?> style="background-color:<?php wpb_bg();?>">>

You can now save your changes and visit your website to see this in action.

现在,您可以保存所做的更改并访问您的网站以查看此操作。

Random background change in WordPress

For more details and alternate methods, see our tutorial on how to randomly change background color in WordPress.

有关更多详细信息和替代方法,请参见有关如何在WordPress中随机更改背景颜色的教程。

8.更新WordPress URL (8. Update WordPress URLs)

If your WordPress login page keeps refreshing or you are unable to access admin area, then you need to update WordPress URLs.

如果您的WordPress登录页面不断刷新,或者您无法访问admin区域 ,则需要更新WordPress URL。

One way to do this is by using wp-config.php file. However, if you do that you will not be able to set the correct address on the settings page. The WordPress URL and Site URL fields will be locked and uneditable.

一种方法是使用wp-config.php文件。 但是,如果这样做,将无法在设置页面上设置正确的地址。 WordPress URL和Site URL字段将被锁定且不可编辑。

If you want to fix this, then you should add this code to your functions file.

如果要解决此问题,则应将此代码添加到功能文件中。

update_option( 'siteurl', 'http://example.com' );update_option( 'home', 'http://example.com' );

Don’t forget to replace example.com with your own domain name.

不要忘记用您自己的域名替换example.com。

Once you are logged in, you can go to Settings and set the URLs there. After that you should remove the code you added to the functions file, otherwise it will keep updating those URLs any time your site is accessed.

登录后,您可以转到“设置”并在此处设置URL。 之后,您应该删除添加到功能文件中的代码,否则,只要您访问站点,它将不断更新这些URL。

9.在WordPress中添加其他图像大小 (9. Add Additional Image Sizes in WordPress)

WordPress automatically creates several image sizes when you upload an image. You can also create additional image sizes to use in your theme. Add this code your theme’s functions file.

当您上传图片时,WordPress会自动创建几种图片尺寸。 您还可以创建其他图像尺寸以用于主题。 将此代码添加到主题的功能文件中。

add_image_size( 'sidebar-thumb', 120, 120, true ); // Hard Crop Modeadd_image_size( 'homepage-thumb', 220, 180 ); // Soft Crop Modeadd_image_size( 'singlepost-thumb', 590, 9999 ); // Unlimited Height Mode

This code creates three new image sizes with different sizes. Feel free to tweak the code to meet your own requirements.

此代码创建三个具有不同尺寸的新图像尺寸。 随意调整代码以满足您自己的要求。

You can display an image size in anywhere in your theme using this code.

您可以使用此代码在主题的任何位置显示图像大小。

<?php the_post_thumbnail( 'homepage-thumb' ); ?>

For detailed instructions, see our guide on how to create additional image sizes in WordPress.

有关详细说明,请参阅有关如何在WordPress中创建其他图像尺寸的指南。

10.向主题添加新的导航菜单 (10. Add New Navigation Menus to Your Theme)

WordPress allows theme developers to define navigation menus and then display them. Add this code in your theme’s functions file to define a new menu location in your theme.

WordPress允许主题开发人员定义导航菜单,然后显示它们。 将此代码添加到主题的功能文件中,以在主题中定义新的菜单位置。

function wpb_custom_new_menu() {register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));}add_action( 'init', 'wpb_custom_new_menu' );

You can now go to Appearance » Menus and you will see ‘My Custom Menu’ as theme location option.

您现在可以转到外观»菜单 ,您将看到“我的自定义菜单”作为主题位置选项。

New navigation menu

Now you need to add this code to your theme where you want to display navigation menu.

现在,您需要将此代码添加到您想要显示导航菜单的主题。

<?phpwp_nav_menu( array( 'theme_location' => 'my-custom-menu', 'container_class' => 'custom-menu-class' ) ); ?>

For detailed instructions, see our guide on how to add custom navigation menus in WordPress themes.

有关详细说明,请参阅有关如何在WordPress主题中添加自定义导航菜单的指南。

11.添加作者个人资料字段 (11. Add Author Profile Fields)

Do you want to add extra fields to your author profiles in WordPress? You can easily do that by adding this code to your functions file:

是否要在WordPress的作者个人资料中添加其他字段? 您可以通过将以下代码添加到函数文件中来轻松实现此目的:

function wpb_new_contactmethods( $contactmethods ) {// Add Twitter$contactmethods['twitter'] = 'Twitter';//add Facebook$contactmethods['facebook'] = 'Facebook';return $contactmethods;}add_filter('user_contactmethods','wpb_new_contactmethods',10,1);

This code will add Twitter and Facebook fields to user profiles in WordPress.

此代码会将Twitter和Facebook字段添加到WordPress中的用户个人资料。

Extra user profile fields in WordPress

You can now display these fields in your author template like this:

您现在可以像这样在作者模板中显示这些字段:

<?php echo $curauth->twitter; ?>

You may also want to see our guide on how to add additional user profile fields in WordPress registration.

您可能还希望查看有关如何在WordPress注册中添加其他用户配置文件字段的指南。

12.在WordPress主题中添加小部件就绪区域或侧边栏 (12. Adding Widget Ready Areas or Sidebar in WordPress Themes)

This is one of the most used ones and many developers already know about this. But it deserves to be in this list for those who don’t know. Paste the following code in your functions.php file:

这是最常用的工具之一,许多开发人员已经知道这一点。 但是对于那些不认识的人,应该将其列入此列表。 将以下代码粘贴到functions.php文件中:

// Register Sidebarsfunction custom_sidebars() {$args = array('id'=> 'custom_sidebar','name'=> __( 'Custom Widget Area', 'text_domain' ),'description' => __( 'A custom widget area', 'text_domain' ),'before_title'=> '<h3 class="widget-title">','after_title' => '</h3>','before_widget' => '<aside id="%1$s" class="widget %2$s">','after_widget'=> '</aside>',);register_sidebar( $args );}add_action( 'widgets_init', 'custom_sidebars' );

You can now visit Appearance » Widgets page and you will see your new custom widget area.

您现在可以访问外观»小部件页面,您将看到新的自定义小部件区域。

Newly registered widget area in WordPress

To display this sidebar or widget ready area in your theme add this code:

要在主题中显示此侧边栏或窗口小部件就绪区域,请添加以下代码:

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('custom_sidebar') ) : ?><!–Default sidebar info goes here–><?php endif; ?>

For more details see our guide on how to add dynamic widget ready areas and sidebars in WordPress.

有关更多详细信息,请参见有关如何在WordPress中添加动态窗口小部件就绪区域和侧边栏的指南

13.操纵RSS feed页脚 (13. Manipulate RSS Feed Footer)

Have you seen blogs that adds their advertisement in their RSS Feeds below each post. You can accomplish that easily with a simple function. Paste the following code:

您是否看到过在每个帖子下方的RSS Feed中添加其广告的博客。 您可以使用简单的功能轻松完成此操作。 粘贴以下代码:

function wpbeginner_postrss($content) {if(is_feed()){$content = 'This post was written by Syed Balkhi '.$content.'Check out WPBeginner';}return $content;}add_filter('the_excerpt_rss', 'wpbeginner_postrss');add_filter('the_content', 'wpbeginner_postrss');

For more information, see our guide on how to add content and completely manipulate your RSS feeds.

有关更多信息,请参见有关如何添加内容和完全操纵RSS feed的指南

14.将特色图像添加到RSS源 (14. Add Featured Images to RSS Feeds)

The post thumbnail or featured images are usually only displayed within your site design. You can easily extend that functionality to your RSS feed with a simple function in your RSS feed.

帖子缩略图或精选图片通常仅在您的网站设计中显示。 您可以通过RSS feed中的简单功能轻松地将该功能扩展到RSS feed。

function rss_post_thumbnail($content) {global $post;if(has_post_thumbnail($post->ID)) {$content = '<p>' . get_the_post_thumbnail($post->ID) .'</p>' . get_the_content();}return $content;}add_filter('the_excerpt_rss', 'rss_post_thumbnail');add_filter('the_content_feed', 'rss_post_thumbnail');

For more details see our guide on how to add post thumbnails to your WordPress RSS feed.

有关更多详细信息,请参阅我们的指南,了解如何将帖子缩略图添加到WordPress RSS feed

15.在WordPress中隐藏登录错误 (15. Hide Login Errors in WordPress)

Login errors in WordPress can be used by hackers to guess whether they entered wrong username or password. By hiding login errors in WordPress you can make your login area a bit more secure.

黑客可以使用WordPress中的登录错误来猜测他们是否输入了错误的用户名或密码。 通过将登录错误隐藏在WordPress中,可以使您的登录区域更加安全。

function no_wordpress_errors(){return 'Something is wrong!';}add_filter( 'login_errors', 'no_wordpress_errors' );

Now users see a generic message when they enter incorrect username or password.

现在,当用户输入错误的用户名或密码时,会看到一条通用消息。

No login hints in WordPress

For more information, see our tutorial on how to disable login hints in WordPress login error messages.

有关更多信息,请参见有关如何在WordPress登录错误消息中禁用登录提示的教程。

16.在WordPress中禁用通过电子邮件登录 (16. Disable Login by Email in WordPress)

WordPress allows users to login with username or email address. You can easily disable login by email in WordPress by adding this code to your functions file.

WordPress允许用户使用用户名或电子邮件地址登录。 您可以通过将此代码添加到功能文件中来轻松禁用WordPress中的电子邮件登录。

remove_filter( 'authenticate', 'wp_authenticate_email_password', 20 );

For more information see our guide on how to disable login by email feature in WordPress.

有关更多信息,请参见有关如何在WordPress中禁用通过电子邮件登录功能的指南。

17.禁用WordPress中的搜索功能 (17. Disable Search Feature in WordPress)

If you want to disable search feature on your WordPress site, then simply add this code to your functions file.

如果要在WordPress网站上禁用搜索功能,则只需将此代码添加到功能文件中即可。

function fb_filter_query( $query, $error = true ) {if ( is_search() ) {$query->is_search = false;$query->query_vars[s] = false;$query->query[s] = false;// to errorif ( $error == true )$query->is_404 = true;}}add_action( 'parse_query', 'fb_filter_query' );add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

For more information, see our tutorial on how to disable search feature in WordPress.

有关更多信息,请参见有关如何在WordPress中禁用搜索功能的教程。

18. RSS Feed中的延迟发布 (18. Delay Posts in RSS Feed)

Sometimes you may end up with a grammar or spelling mistake in your article. The mistake goes live and is distributed to your RSS feed subscribers. If you have email subscriptions on your WordPress blog, then those subscribers will get it as well.

有时,您可能会在文章中出现语法或拼写错误。 该错误会继续存在,并分发给您的RSS feed订阅者。 如果您在WordPress博客上有电子邮件订阅 ,那么这些订阅者也将获得它。

Simply add this code in your theme’s functions file.

只需将此代码添加到主题的功能文件中即可。

function publish_later_on_feed($where) {global $wpdb;if ( is_feed() ) {// timestamp in WP-format$now = gmdate('Y-m-d H:i:s');// value for wait; + device$wait = '10'; // integer// http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff$device = 'MINUTE'; //MINUTE, HOUR, DAY, WEEK, MONTH, YEAR// add SQL-sytax to default $where$where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";}return $where;}add_filter('posts_where', 'publish_later_on_feed');

In this code we have used 10 minutes as $wait or delay time. Feel free to change that into any number of minutes you want.

在此代码中,我们将10分钟用作$ wait或延迟时间。 随意将其更改为所需的任何分钟数。

For plugin method and more information, see our detailed guide on how to delay posts from appearing in WordPress RSS feed.

有关插件方法和更多信息,请参见有关如何延迟帖子在WordPress RSS feed中出现的详细指南。

19.更改WordPress摘录中的更多阅读文本 (19. Change Read More Text for Excerpts in WordPress)

Do you want to change the text that appears after the excerpt? Simply add this code to your theme’s functions file.

您是否要更改摘录后出现的文本? 只需将此代码添加到主题的功能文件中即可。

function modify_read_more_link() {return '<a class="more-link" href="' . get_permalink() . '">Your Read More Link Text</a>';}add_filter( 'the_content_more_link', 'modify_read_more_link' );

20.禁用WordPress中的RSS源 (20. Disable RSS Feeds in WordPress)

Not all websites need RSS feeds. If you want to disable RSS feeds on your WordPress site, then add this code to your theme’s functions file.

并非所有网站都需要RSS feed。 如果要在WordPress站点上禁用RSS feed,则将此代码添加到主题的功能文件中。

function fb_disable_feed() {wp_die( __('No feed available,please visit our <a href="'. get_bloginfo('url') .'">homepage</a>!') );}add_action('do_feed', 'fb_disable_feed', 1);add_action('do_feed_rdf', 'fb_disable_feed', 1);add_action('do_feed_rss', 'fb_disable_feed', 1);add_action('do_feed_rss2', 'fb_disable_feed', 1);add_action('do_feed_atom', 'fb_disable_feed', 1);

For a plugin method and more information, see our guide on how to disable RSS feeds in WordPress.

有关插件方法和更多信息,请参见有关如何在WordPress中禁用RSS feed的指南。

21.在WordPress中更改摘录长度 (21. Change Excerpt Length in WordPress)

WordPress limits excerpt lengths to 55 words. If you need to change that, then you can add this code to your functions file.

WordPress将摘录长度限制为55个字。 如果需要更改,则可以将此代码添加到函数文件中。

function new_excerpt_length($length) {return 100;}add_filter('excerpt_length', 'new_excerpt_length');

Change 100 to the number of words you want to show in the excerpts.

将要在摘录中显示的单词数更改为100。

For alternate method, you may want to take a look at our guide on how to customize WordPress excerpts (no coding required).

对于替代方法,您可能需要看一下我们的指南,以了解如何自定义WordPress摘录(无需编码)

22.在WordPress中添加管理员用户 (22. Add an Admin User in WordPress)

If you have forgotten your WordPress password and email, then you can add an admin user by adding this code to your theme’s functions file using an FTP client.

如果您忘记了WordPress密码和电子邮件,则可以通过使用FTP客户端将此代码添加到主题的功能文件中来添加管理员用户。

function wpb_admin_account(){$user = 'Username';$pass = 'Password';$email = 'email@domain.com';if ( !username_exists( $user )&& !email_exists( $email ) ) {$user_id = wp_create_user( $user, $pass, $email );$user = new WP_User( $user_id );$user->set_role( 'administrator' );} }add_action('init','wpb_admin_account');

Don’t forget to fill in the username, password, and email fields. Once you login to your WordPress site, don’t forget to delete the code from your functions file.

不要忘记填写用户名,密码和电子邮件字段。 登录到WordPress网站后,请不要忘记从功能文件中删除代码。

For more on this topic, take a look at our tutorial on how to add an admin user in WordPress using FTP.

有关此主题的更多信息,请查看我们的教程, 教程如何使用WordPress在WordPress中添加管理员用户

23.从WordPress仪表板上删除“欢迎面板” (23. Remove Welcome Panel from WordPress Dashboard)

Welcome panel is a meta box added to the dashboard screen of WordPress admin area. It provides useful shortcuts for beginners to do things on their new WordPress site.

欢迎面板是一个添加到WordPress管理区域的仪表板屏幕的meta框。 它为初学者在新的WordPress网站上做事提供了有用的快捷方式。

Welcome panel in WordPress admin dashboard

You can easily hide by adding this code in your functions file.

您可以通过在函数文件中添加此代码来轻松隐藏。

remove_action('welcome_panel', 'wp_welcome_panel');

For other methods and more details check out our guide on how to remove welcome panel in WordPress dashboard.

有关其他方法和更多详细信息,请查看有关如何在WordPress仪表板中删除欢迎面板的指南。

24.显示WordPress中已注册用户的总数 (24. Show Total Number of Registered Users in WordPress)

Do you want to show total number of registered users on your WordPress site? Simply add this code to your theme’s functions file.

您想显示您的WordPress网站上的注册用户总数吗? 只需将此代码添加到主题的功能文件中即可。

// Function to return user countfunction wpb_user_count() { $usercount = count_users();$result = $usercount['total_users']; return $result; } // Creating a shortcode to display user countadd_shortcode('user_count', 'wpb_user_count');

This code creates a shortcode that allows you to display total number of registered users on your site. Now you just need to add this shortcode to [user_count] your post or page where you want to show the total number of users.

此代码创建了一个短代码,可让您显示站点上已注册用户的总数。 现在,您只需要将此简码添加到您要显示用户总数的帖子或页面的[user_count]。

For more information and a plugin method, see our tutorial on how to display total number of registered users in WordPress.

有关更多信息和插件方法,请参见有关如何显示WordPress中注册用户总数的教程。

25.从RSS Feed中排除特定类别 (25. Exclude Specific Categories from RSS Feed)

Do you want to exclude specific categories from your WordPress RSS feed? Add this code to your theme’s functions file.

您是否要从WordPress RSS feed中排除特定类别? 将此代码添加到主题的功能文件中。

function exclude_category($query) {if ( $query->is_feed ) {$query->set('cat', '-5, -2, -3');}return $query;}add_filter('pre_get_posts', 'exclude_category');

26.在文本小部件中启用简码执行 (26. Enable Shortcode Execution in Text Widgets)

By default, WordPress does not execute shortcodes inside text widgets. To fix this you need to simply add this code to your theme’s functions file.

默认情况下,WordPress不会在文本小部件内执行简码。 要解决此问题,您只需将此代码添加到主题的功能文件中即可。

// Enable shortcodes in text widgetsadd_filter('widget_text','do_shortcode');

For an alternate method and more information, take a look at our guide on how to use shortcodes in WordPress sidebar widgets.

有关替代方法和更多信息,请查看有关如何在WordPress边栏小部件中使用短代码的指南。

27.将奇数和偶数CSS类添加到WordPress帖子中 (27. Add Odd and Even CSS Classes to WordPress Posts)

You may have seen WordPress themes using an old or even class for WordPress comments. It helps users visualize where one comment ends and the next one begins.

您可能已经看到WordPress主题使用旧的甚至是WordPress注释类。 它可以帮助用户可视化一个评论的结尾和下一个评论的起点。

You can use the same technique for your WordPress posts. It looks aesthetically pleasing and helps users quickly scan pages with lots of content. Simply add this code to your theme’s functions file.

您可以对WordPress帖子使用相同的技术。 它看起来在美学上令人愉悦,并可以帮助用户快速扫描包含大量内容的页面。 只需将此代码添加到主题的功能文件中即可。

function oddeven_post_class ( $classes ) { global $current_class; $classes[] = $current_class; $current_class = ($current_class == 'odd') ? 'even' : 'odd'; return $classes;}add_filter ( 'post_class' , 'oddeven_post_class' );global $current_class;$current_class = 'odd';

This code simply adds an odd or even class to WordPress posts. You can now add custom CSS to style them differently. Here is a sample code to help you get started.

这段代码只是在WordPress帖子中添加了一个奇数或偶数类。 现在,您可以添加自定义CSS,以采用不同的样式。 这是一个示例代码,可以帮助您入门。

.even {background:#f0f8ff;} .odd { background:#f4f4fb;}

The end result will look something like this:

最终结果将如下所示:

Alternate colors used for WordPress posts using odd and even CSS classes

Need more detailed instructions? Take a look at our tutorial on how to add odd/even class to your post in WordPress themes.

需要更详细的说明吗? 看看我们的教程, 如何在WordPress主题中为帖子添加奇/偶类

28.添加要在WordPress中上传的其他文件类型 (28. Add Additional File Types to be Uploaded in WordPress)

By default, WordPress allows you to upload a limited number of most commonly used file types. However, you can extend it to allow other file types. Add this code to your theme’s functions file:

默认情况下,WordPress允许您上传有限数量的最常用文件类型。 但是,您可以扩展它以允许其他文件类型。 将此代码添加到主题的功能文件中:

function my_myme_types($mime_types){$mime_types['svg'] = 'image/svg+xml'; //Adding svg extension$mime_types['psd'] = 'image/vnd.adobe.photoshop'; //Adding photoshop filesreturn $mime_types;}add_filter('upload_mimes', 'my_myme_types', 1, 1);

This code allows you to upload SVG and PSD files to WordPress. You will need to Google to find out the mime types for the file types you want to allow and then use it in the code.

此代码允许您将SVG和PSD文件上传到WordPress。 您将需要Google找出您要允许的文件类型的mime类型,然后在代码中使用它。

For more on this topic, check out our tutorial on how to add additional file types to be uploaded in WordPress.

有关此主题的更多信息,请查看有关如何添加要在WordPress中上传的其他文件类型的教程。

By default, when you upload an image in WordPress it is automatically linked to the image file or the attachment page. If users click on the image they are then taken to a new page away from your post.

默认情况下,当您在WordPress中上传图片时,它会自动链接到图片文件或附件页面。 如果用户单击图像,他们将被带到远离您帖子的新页面。

Here is how you can easily stop WordPress from automatically linking image uploads. All you have to do is to add this code snippet to your functions file:

这是您可以轻松阻止WordPress自动链接图像上传的方法。 您要做的就是将以下代码片段添加到您的功能文件中:

function wpb_imagelink_setup() {$image_set = get_option( 'image_default_link_type' );if ($image_set !== 'none') {update_option('image_default_link_type', 'none');}}add_action('admin_init', 'wpb_imagelink_setup', 10);

Now when you upload a new image in WordPress, it will not be automatically linked. You can still link it to the file or attachment page if you want.

现在,当您在WordPress中上载新图像时,它将不会自动链接。 如果需要,您仍然可以将其链接到文件或附件页面。

Disable default image links in WordPress

You may want to check out our tutorial on how to remove default image links in WordPress for an alternate plugin method and more information.

您可能要查看有关如何在WordPress中删除默认图像链接的教程, 获得替代的插件方法和更多信息。

30.在WordPress帖子中添加作者信息框 (30. Add an Author Info Box in WordPress Posts)

If you run a multi-author site and want to showcase author bios at the end of your post, then you can try this method. Start by adding this code to your functions file:

如果您运行一个多作者网站,并希望在帖子末尾展示作者的简历,则可以尝试这种方法。 首先将此代码添加到您的功能文件中:

function wpb_author_info_box( $content ) {global $post;// Detect if it is a single post with a post authorif ( is_single() && isset( $post->post_author ) ) {// Get author's display name $display_name = get_the_author_meta( 'display_name', $post->post_author );// If display name is not available then use nickname as display nameif ( empty( $display_name ) )$display_name = get_the_author_meta( 'nickname', $post->post_author );// Get author's biographical information or description$user_description = get_the_author_meta( 'user_description', $post->post_author );// Get author's website URL $user_website = get_the_author_meta('url', $post->post_author);// Get link to the author archive page$user_posts = get_author_posts_url( get_the_author_meta( 'ID' , $post->post_author)); if ( ! empty( $display_name ) )$author_details = '<p class="author_name">About ' . $display_name . '</p>';if ( ! empty( $user_description ) )// Author avatar and bio$author_details .= '<p class="author_details">' . get_avatar( get_the_author_meta('user_email') , 90 ) . nl2br( $user_description ). '</p>';$author_details .= '<p class="author_links"><a href="'. $user_posts .'">View all posts by ' . $display_name . '</a>';// Check if author has a website in their profileif ( ! empty( $user_website ) ) {// Display author website link$author_details .= ' | <a href="' . $user_website .'" target="_blank" rel="nofollow">Website</a></p>';} else { // if there is no author website then just close the paragraph$author_details .= '</p>';}// Pass all this info to post content$content = $content . '<footer class="author_bio_section" >' . $author_details . '</footer>';}return $content;}// Add our function to the post content filter add_action( 'the_content', 'wpb_author_info_box' );// Allow HTML in author bio section remove_filter('pre_user_description', 'wp_filter_kses');

Next you will need to add some custom CSS to make it look better. You can use this sample CSS as an starting point.

接下来,您将需要添加一些自定义CSS使其看起来更好。 您可以使用此样本CSS作为起点。

.author_bio_section{background: none repeat scroll 0 0 #F5F5F5;padding: 15px;border: 1px solid #ccc;}.author_name{font-size:16px;font-weight: bold;}.author_details img {border: 1px solid #D8D8D8;border-radius: 50%;float: left;margin: 0 10px 10px 0;}

This is how your author box would look like:

这是您的作者框的外观:

Author box

For plugin method and more detailed instructions, check out our article on how to add an author info box in WordPress posts.

有关插件方法和更多详细说明,请查看我们有关如何在WordPress帖子中添加作者信息框的文章

31.在WordPress中禁用XML-RPC (31. Disable XML-RPC in WordPress)

XML-RPC is a method that allows third party apps to communicate with your WordPress site remotely. This could cause security issues and can be exploited by hackers.

XML-RPC是一种允许第三方应用程序与WordPress站点进行远程通信的方法。 这可能会导致安全问题,并可能被黑客利用。

Simply add this code to your functions file to turn off XML-RPC in WordPress:

只需将以下代码添加到您的函数文件中,即可在WordPress中关闭XML-RPC:

add_filter('xmlrpc_enabled', '__return_false');

You may want to read our article on how to disable XML-RPC in WordPress for more information.

您可能需要阅读有关如何在WordPress中禁用XML-RPC的文章, 获取更多信息。

32.自动将特色图像链接到帖子 (32. Automatically Link Featured Images to Posts)

If your WordPress theme does not automatically link featured images to full articles, then you can try this method. Simply add this code to your theme’s functions file.

如果您的WordPress主题没有自动将特色图片链接到全文,则可以尝试这种方法。 只需将此代码添加到主题的功能文件中即可。

function wpb_autolink_featured_images( $html, $post_id, $post_image_id ) {If (! is_singular()) { $html = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( get_the_title( $post_id ) ) . '">' . $html . '</a>';return $html;} else { return $html;}}add_filter( 'post_thumbnail_html', 'wpb_autolink_featured_images', 10, 3 );

You may want to read our article on how to automatically link featured images to posts in WordPress.

您可能需要阅读有关如何自动将特色图像链接到WordPress中的帖子的文章

That’s all for now.

目前为止就这样了。

We hope this article helped you learn some new useful tricks for functions.php file in WordPress. You may also want to see our ultimate guide to boost WordPress speed and performance.

我们希望本文能帮助您学习WordPress中functions.php文件的一些新有用技巧。 您可能还需要查看我们的终极指南,以提高WordPress的速度和性能

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

如果您喜欢这篇文章,请订阅我们的YouTube频道 WordPress视频教程。 您也可以在TwitterFacebook上找到我们。

翻译自: https://www.wpbeginner.com/wp-tutorials/25-extremely-useful-tricks-for-the-wordpress-functions-file/

wordpress 函数

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}