和许多正在查看此帖子的其他人一样,我一直在阅读各种博客,论坛和讨论组,以学习和提高我的WordPress技能。在过去的12个月中,我一直致力于通过向我的functions.php文件中添加代码来替代我对插件的使用。

虽然我完全同意插件在许多情况下都非常有用,但我的经验证明在90%的使用情况下,尽管可能存在一个插件,但实际使用它可能会造成不必要的复杂性和兼容性问题。此外,在很多情况下,此类插件添加了我不需要或不需要的菜单和其他管理元素。

我经常通过分析插件的代码发现,我能够剥离我想要的代码并将其硬编码到我的functions.php中。这为我提供了所需的确切功能,而不必包含不必要的元素。

所以,本文的目的是我试图吸引您(读者/管理员/开发人员)与我分享并其他此处您认为有用且已添加到主题的function.php文件中的任何代码位,无需使用插件即可扩展或增强WordPress。

在此处提交回复时,请给每个代码位一个标题,让我们知道您是否知道与WordPress的哪个版本兼容,包括您认为最能描述其功能的描述,以及(如果适用)包括指向原始插件或您在其中找到信息的源的链接。

我很期待您的所有答复,并且当然会在发现新发现时不断添加我自己的新发现。

请通过单击向上箭头对问题和发现有用的答案进行投票在问题或答案的左侧。


评论

考虑到前5个答案是由OP提出的,并且该问题似乎更适合于收集一系列答案,而不是一个确定的答案,所以这应该是社区Wiki。

与主题无关的所有答案都应删除。此线程是不良编码实践的一个很好的例子。

我认为最好鼓励人们创建自定义功能插件,而不要使用其主题的功能。php

@ NetConstructor.com纯粹的页面浏览量不是质量的指标。我们应该鼓励使用特定答案和良好编码习惯的特定问题。该线程是相反的。

@ NetConstructor.com在Meta上进行讨论,人们可以更好地看到您的论点。 :)

#1 楼

启用显示所有站点设置的隐藏管理功能
在WordPress 3.1 RC3上进行了测试
这小段代码确实很酷。它将在您的设置菜单中添加一个附加选项,并带有指向“所有设置”的链接,该链接将向您显示数据库中与WordPress网站相关的所有设置的完整列表。以下代码仅会使管理员用户看到此链接,并为所有其他用户隐藏此链接。
// CUSTOM ADMIN MENU LINK FOR ALL SETTINGS
   function all_settings_link() {
    add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
   }
   add_action('admin_menu', 'all_settings_link');


评论


神奇的发展!我经常使用选项表来存储插件的数据库版本...使用phpMyAdmin重置为旧的数据库版本以测试升级脚本是一件痛苦的事……这将使它变得如此简单!

–EAMann
2010-09-15 16:03

您还可以通过访问yoursite / wp-admin / options.php进入相同的选项页面(登录时)。

– j08691
2015年10月9日19:55

#2 楼

修改登录徽标和图像URL链接
在WordPress 3.0.1上进行了测试
该代码将使您可以轻松地修改WordPress登录页面徽标以及该徽标的href链接和标题文本。 br />
add_filter( 'login_headerurl', 'namespace_login_headerurl' );
/**
 * Replaces the login header logo URL
 *
 * @param $url
 */
function namespace_login_headerurl( $url ) {
    $url = home_url( '/' );
    return $url;
}

add_filter( 'login_headertitle', 'namespace_login_headertitle' );
/**
 * Replaces the login header logo title
 *
 * @param $title
 */
function namespace_login_headertitle( $title ) {
    $title = get_bloginfo( 'name' );
    return $title;
}

add_action( 'login_head', 'namespace_login_style' );
/**
 * Replaces the login header logo
 */
function namespace_login_style() {
    echo '<style>.login h1 a { background-image: url( ' . get_template_directory_uri() . '/images/logo.png ) !important; }</style>';
}

编辑:如果要使用站点徽标代替登录徽标,则可以使用以下内容动态提取该信息(在WP3.5上进行了测试):
function namespace_login_style() {
    if( function_exists('get_custom_header') ){
        $width = get_custom_header()->width;
        $height = get_custom_header()->height;
    } else {
        $width = HEADER_IMAGE_WIDTH;
        $height = HEADER_IMAGE_HEIGHT;
    }
    echo '<style>'.PHP_EOL;
    echo '.login h1 a {'.PHP_EOL; 
    echo '  background-image: url( '; header_image(); echo ' ) !important; '.PHP_EOL;
    echo '  width: '.$width.'px !important;'.PHP_EOL;
    echo '  height: '.$height.'px !important;'.PHP_EOL;
    echo '  background-size: '.$width.'px '.$height.'px !important;'.PHP_EOL;
    echo '}'.PHP_EOL;
    echo '</style>'.PHP_EOL;
}


#3 楼

在搜索结果中包括自定义帖子类型。
// MAKE CUSTOM POST TYPES SEARCHABLE
function searchAll( $query ) {
 if ( $query->is_search ) { $query->set( 'post_type', array( 'site', 'plugin', 'theme', 'person' )); } 
 return $query;
}
add_filter( 'the_search_query', 'searchAll' );

默认情况下将自定义帖子类型添加到站点主RSS feed。
// ADD CUSTOM POST TYPES TO THE DEFAULT RSS FEED
function custom_feed_request( $vars ) {
 if (isset($vars['feed']) && !isset($vars['post_type']))
  $vars['post_type'] = array( 'post', 'site', 'plugin', 'theme', 'person' );
 return $vars;
}
add_filter( 'request', 'custom_feed_request' );

在“立即”中包括自定义帖子类型。管理员信息中心小部件
,这将包括您的自定义帖子类型以及“立即”信息中心小部件中每种类型的帖子计数。

评论


关于此答案的最后一个片段。这是一个很棒的补充,因为我为每种帖子类型手动添加了这些。我对此唯一的问题是它将数据添加到默认的“类别”和“标签”条目之后。您能否更新答案以将默认的“类别”或“标记”项下移或删除,以便可以手动添加?

– NetConstructor.com
2011-2-22在20:06

@ NetConstructor.com我认为我不理解您的要求。如果我这样做了,那么我认为这将是一件困难的事情,并且现在还没有真正的时间去弄清楚该怎么做。

– jaredwilli
2011-2-23在1:01

在搜索结果中包含自定义帖子类型-我想,现在您可以使用register_post_type的exclude_from_search参数来执行此操作...

– KrzysiekDróżdż♦
2013年12月16日下午16:13

#4 楼

删除除ADMIN用户以外的所有用户的更新通知。
在WordPress 3.0.1上进行了测试。此代码将确保在更新可用时,WordPress不会通知除“ admin”以外的任何用户。.
// REMOVE THE WORDPRESS UPDATE NOTIFICATION FOR ALL USERS EXCEPT SYSADMIN
   global $user_login;
   get_currentuserinfo();
   if ($user_login !== "admin") { // Change admin to the username that gets the updates
    add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
    add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
   }

更改版本以仅显示admin用户的更新通知(而不只是用户'admin'):
// REMOVE THE WORDPRESS UPDATE NOTIFICATION FOR ALL USERS EXCEPT SYSADMIN
       global $user_login;
       get_currentuserinfo();
       if (!current_user_can('update_plugins')) { // Checks to see if current user can update plugins
        add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
        add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
       }


评论


这远远不理想。仅当管理员的登录名仍然是默认的“ admin”时,它才起作用,出于安全原因,不应使用该名称。相反,您应该检查希望人们看到消息的特定功能。

–jerclarke
2010-09-11 20:28

即如果(!current_user_can('manage_options')){... add_filter ...}-对不起,我有双重评论,我忘了按回车键提交评论)

–jerclarke
2010-09-11 20:29

这就是为什么我在代码中添加注释的地方,您可以在其中更改管理员用户名。您将如何改善/重写它?

– NetConstructor.com
2010-09-12 9:07

最好的方法是删除全局$ user_login和get_currentuserinfo(),而在if子句中使用current_user_can。它只有1行,而不是3行及其标准方式。您可以检查对消息进行ACT所需的特定功能,在这种情况下,具有“ update_core”和“ update_plugins”。

–jerclarke
2010-09-12的14:00

因此:if(!current_user_can('update_plugins')){/ *删除邮件* /}

–jerclarke
2010-09-12 14:01

#5 楼

从Google CDN加载jQuery

经过以下测试:WordPress 3.0.1

// Even more smart jQuery inclusion :)
add_action( 'init', 'jquery_register' );

// Register from Google and for footer
function jquery_register() {

    if ( !is_admin() ) {

        wp_deregister_script( 'jquery' );
        wp_register_script( 'jquery', ( 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js' ), false, null, true );
        wp_enqueue_script( 'jquery' );
    }
}


删除WordPress版本信息以获得安全性

经过测试:WordPress 3.0.1

// Remove version info from head and feeds
function complete_version_removal() {
    return '';
}
add_filter('the_generator', 'complete_version_removal');

添加垃圾邮件并删除指向评论前端的链接

经过测试:WordPress 3.0 .1

通过添加垃圾邮件和删除链接,可以更轻松地从前端管理评论。**

// Spam & delete links for all versions of WordPress
function delete_comment_link($id) {
    if (current_user_can('edit_post')) {
        echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&c='.$id.'">del</a> ';
        echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&dt=spam&c='.$id.'">spam</a>';
    }
}


公开发布到RSS提要

在WordPress 3.0.1上进行了测试

最后,我希望将发布到RSS提要的时间延迟10-15分钟,因为我总是发现至少我的文字中有几个错误。其他用途是在您希望将内容发布到RSS阅读器之前在一天或一周内专有于您的网站的情况。

// Delay feed update
function publish_later_on_feed($where) {
    global $wpdb;

    if (is_feed()) {
        // Timestamp in WordPress 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 syntax to default $where
        $where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";
    }
    return $where;
}
add_filter('posts_where', 'publish_later_on_feed');


评论


我的帖子上的资源:wpengineer.com/320/publish-the-feed-later,包含更多信息

– Bueltge
2010-09-17在8:29

您也可以只删除生成器过滤器:remove_action('wp_head','wp_generator');

–Gipetto
2010-09-18在7:01

ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js会在一个小时后过期。始终使用完整版本信息,例如ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js –会在一年后过期。

– fuxia♦
2010-11-10 14:41



“删除WordPress版本信息以提高安全性”代码实际上并没有采取任何措施来提高您网站的安全性。它甚至没有停止公开您网站上正在使用的WP版本。

–约瑟夫·斯科特(Joseph Scott)
2011年2月11日下午6:38

不对,约瑟夫,如果您的WordPress版本已公开,则人们可以查看您是否正在运行旧版本,从而暴露了您的漏洞。从所有WordPress安装中删除它始终是一个好决定。就个人而言,我什至不知道为什么将它们放在第一位,因为这是一个安全问题。

–杰里米
2014年5月12日15:51

#6 楼

设置最大的修订版本数以避免DB膨胀。
测试于:WordPress 3.0.1
默认值是无穷大,它将设置为仅记住最后五个编辑:
/**
 * Set the post revisions unless the constant was set in wp-config.php
 */
if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', 5);

关于其价值,有很多关于CONSTANTS的好主意,可以在Codex页面上编辑wp-config.php。

评论


可以基于每个帖子类型设置吗?

– NetConstructor.com
2010-09-12 9:17

在wp_save_post_revision()中查看它的用法,似乎没有一种方法可以根据帖子类型进行区分。尽管可能应该有过滤器或值上的任何内容。

–jerclarke
2010-09-12 14:24

感谢Jeremy-对其他人,如果您知道如何执行此操作,请在此处发布。

– NetConstructor.com
2010-09-14 7:18

我个人更喜欢10。我知道它是两倍,但是当我需要修订时,它总是比5老。

– w
2012年9月4日在12:04

#7 楼

WordPress分析工具
我想在一个单独的文件中添加分析工具,然后在需要时将其包含在functions.php中:
<?php
    if ( !defined('SAVEQUERIES') && isset($_GET['debug']) && $_GET['debug'] == 'sql' )
        define('SAVEQUERIES', true);

    if ( !function_exists('dump') ) :
        /**
         * dump()
         *
         * @param mixed $in
         * @return mixed $in
         **/

        function dump($in = null) {
            echo '<pre style="margin-left: 0px; margin-right: 0px; padding: 10px; border: solid 1px black; background-color: ghostwhite; color: black; text-align: left;">';
            foreach ( func_get_args() as $var ) {
                echo "\n";
                if ( is_string($var) ) {
                    echo "$var\n";
                } else {
                    var_dump($var);
                }
            }
            echo '</pre>' . "\n";
            return $in;
        } # dump()
    endif;

    /**
     * add_stop()
     *
     * @param mixed $in
     * @param string $where
     * @return mixed $in
     **/

    function add_stop($in = null, $where = null) {
        global $sem_stops;
        global $wp_object_cache;
        $queries = get_num_queries();
        $milliseconds = timer_stop() * 1000;
        $out =  "$queries queries - {$milliseconds}ms";
        if ( function_exists('memory_get_usage') ) {
            $memory = number_format(memory_get_usage() / ( 1024 * 1024 ), 1);
            $out .= " - {$memory}MB";
        }
        $out .= " - $wp_object_cache->cache_hits cache hits / " . ( $wp_object_cache->cache_hits + $wp_object_cache->cache_misses );
        if ( $where ) {
            $sem_stops[$where] = $out;
        } else {
            dump($out);
        }
        return $in;
    } # add_stop()


    /**
     * dump_stops()
     *
     * @param mixed $in
     * @return mixed $in
     **/

    function dump_stops($in = null) {

        if ( $_POST )
            return $in;

        global $sem_stops;
        global $wp_object_cache;
        $stops = '';

        foreach ( $sem_stops as $where => $stop )
            $stops .= "$where: $stop\n";

        dump("\n" . trim($stops) . "\n");

        if ( defined('SAVEQUERIES') && $_GET['debug'] == 'sql' ) {
            global $wpdb;
            foreach ( $wpdb->queries as $key => $data ) {
                $query = rtrim($data[0]);
                $duration = number_format($data[1] * 1000, 1) . 'ms';
                $loc = trim($data[2]);
                $loc = preg_replace("/(require|include)(_once)?,\s*/ix", '', $loc);
                $loc = "\n" . preg_replace("/,\s*/", ",\n", $loc) . "\n";
                dump($query, $duration, $loc);
            }
        }

        if ( $_GET['debug'] == 'cache' )
            dump($wp_object_cache->cache);

        if ( $_GET['debug'] == 'cron' ) {
            $crons = get_option('cron');

            foreach ( $crons as $time => $_crons ) {

                if ( !is_array($_crons) )
                    continue;

                foreach ( $_crons as $event => $_cron ) {
                    foreach ( $_cron as $details ) {
                        $date = date('Y-m-d H:m:i', $time);
                        $schedule = isset($details['schedule']) ? "({$details['schedule']})" : '';
                        if ( $details['args'] )
                            dump("$date: $event $schedule", $details['args']);
                        else
                            dump("$date: $event $schedule");
                    }
                }
            }
        }
        return $in;
    } # dump_stops()
    add_action('init', create_function('$in', '
        return add_stop($in, "Load");
        '), 10000000);
    add_action('template_redirect', create_function('$in', '
        return add_stop($in, "Query");
        '), -10000000);
    add_action('wp_footer', create_function('$in', '
        return add_stop($in, "Display");
        '), 10000000);
    add_action('admin_footer', create_function('$in', '
        return add_stop($in, "Display");
        '), 10000000);

    /**
     * init_dump()
     *
     * @return void
     **/

    function init_dump() {
        global $hook_suffix;
        if ( !is_admin() || empty($hook_suffix) ) {
            add_action('wp_footer', 'dump_stops', 10000000);
            add_action('admin_footer', 'dump_stops', 10000000);
        } else {
            add_action('wp_footer', 'dump_stops', 10000000);
            add_action("admin_footer-$hook_suffix", 'dump_stops', 10000000);
        }
    } # init_dump()
    add_action('wp_print_scripts', 'init_dump');


    /**
     * dump_phpinfo()
     *
     * @return void
     **/

    function dump_phpinfo() {
        if ( isset($_GET['debug']) && $_GET['debug'] == 'phpinfo' ) {
            phpinfo();
            die;
        }
    } # dump_phpinfo()
    add_action('init', 'dump_phpinfo');


    /**
     * dump_http()
     *
     * @param array $args
     * @param string $url
     * @return array $args
     **/

    function dump_http($args, $url) {
        dump(preg_replace("|/[0-9a-f]{32}/?$|", '', $url));
        return $args;
    } # dump_http()


    /**
     * dump_trace()
     *
     * @return void
     **/

    function dump_trace() {
        $backtrace = debug_backtrace();
        foreach ( $backtrace as $trace )
            dump(
                'File/Line: ' . $trace['file'] . ', ' . $trace['line'],
                'Function / Class: ' . $trace['function'] . ', ' . $trace['class']
                );
    } # dump_trace()
    if ( $_GET['debug'] == 'http' )
        add_filter('http_request_args', 'dump_http', 0, 2);
?>


评论


有没有一种快速的方法来修改它,以便仅在管理员时才调用脚本,并在URL上附加一些内容以显示调试信息?

– NetConstructor.com
2011-2-22在19:58

这就是我的主题的工作方式:semiologic.com/software/sem-reloaded-/inc/debug.php包含在/functions.php或/inc/init.php中(无法记住我的顶部头)。

–丹尼斯·伯纳迪(Denis de Bernardy)
2011-2-23在9:50

#8 楼

锐化调整大小的图像(仅JPEG)

此功能锐化调整大小的JPEG图像。区别的示例:



function ajx_sharpen_resized_files( $resized_file ) {

    $image = wp_load_image( $resized_file );
    if ( !is_resource( $image ) )
        return new WP_Error( 'error_loading_image', $image, $file );

    $size = @getimagesize( $resized_file );
    if ( !$size )
        return new WP_Error('invalid_image', __('Could not read image size'), $file);
    list($orig_w, $orig_h, $orig_type) = $size;

    switch ( $orig_type ) {

        case IMAGETYPE_JPEG:
            $matrix = array(
                array(-1, -1, -1),
                array(-1, 16, -1),
                array(-1, -1, -1),
            );

            $divisor = array_sum(array_map('array_sum', $matrix));
            $offset = 0;
            imageconvolution($image, $matrix, $divisor, $offset);
            imagejpeg($image, $resized_file,apply_filters( 'jpeg_quality', 90, 'edit_image' ));
            break;

        case IMAGETYPE_PNG:
            return $resized_file;

        case IMAGETYPE_GIF:
            return $resized_file;
    }

    return $resized_file;
}

add_filter('image_make_intermediate_size', 'ajx_sharpen_resized_files', 900);


评论


更好的jpeg,非常感谢!在3.4-alpha中测试

–brasofilo
2012年4月2日在12:07

如果你们想要这个作为插件:wordpress.org/extend/plugins/sharpen-resized-images

–Ünsal Korkmaz
2012年4月3日,9:38

这个功能去哪儿了?

– SteveD
19年3月18日在2:04

@StevieD-顾名思义,它位于模板中的functions.php中。不过,我会小心一点,该功能已有8年历史了。

–timofey.com
19年7月25日在7:54

#9 楼

删除默认的WordPress Meta Box
在WordPress 3.0.1上进行了测试
此代码将允许您删除WordPress默认添加到默认的“添加/编辑帖子”和“添加/编辑页面”屏幕的特定Meta Box。 br />
// REMOVE META BOXES FROM DEFAULT POSTS SCREEN
function remove_default_post_screen_metaboxes() {
    remove_meta_box( 'postcustom','post','normal' ); // Custom Fields Metabox
    remove_meta_box( 'postexcerpt','post','normal' ); // Excerpt Metabox
    remove_meta_box( 'commentstatusdiv','post','normal' ); // Comments Metabox
    remove_meta_box( 'trackbacksdiv','post','normal' ); // Talkback Metabox
    remove_meta_box( 'slugdiv','post','normal' ); // Slug Metabox
    remove_meta_box( 'authordiv','post','normal' ); // Author Metabox
}
add_action('admin_menu', 'remove_default_post_screen_metaboxes');


// REMOVE META BOXES FROM DEFAULT PAGES SCREEN
function remove_default_page_screen_metaboxes() {
    remove_meta_box( 'postcustom','page','normal' ); // Custom Fields Metabox
    remove_meta_box( 'postexcerpt','page','normal' ); // Excerpt Metabox
    remove_meta_box( 'commentstatusdiv','page','normal' ); // Comments Metabox
    remove_meta_box( 'trackbacksdiv','page','normal' ); // Talkback Metabox
    remove_meta_box( 'slugdiv','page','normal' ); // Slug Metabox
    remove_meta_box( 'authordiv','page','normal' ); // Author Metabox
}
add_action('admin_menu', 'remove_default_page_screen_metaboxes');


评论


根据这个wordpress.stackexchange.com/questions/34030/…,我不会以这种方式隐藏slugdiv,而是改用gist.github.com/1863830

–user5424
2012年2月19日在13:25



@CorvanNoorloos您的github链接已损坏。

–user7003859
17-2-26在16:54

#10 楼

删除“ WordPress”到“ WordPress”过滤器
在WordPress 3.0.1上进行了测试
WordPress 3.0版添加了一个过滤器,该过滤器自动将“ Wordpress”(无大写字母P)的所有实例转换为“ WordPress”帖子内容,帖子标题和评论文本中使用“”(大写P)。有人认为这是侵入性的,但我只需要不时对WordPress进行大小写错误,并发现过滤器有些烦人。
// Remove annoying P filter
if(function_exists('capital_P_dangit')) {
    foreach ( array( 'the_content', 'the_title' ) as $filter )
        remove_filter( $filter, 'capital_P_dangit', 11 );

    remove_filter('comment_text', 'capital_P_dangit', 31 );
}


评论


很好的发现。其中一件事情就是删除了不需要的另一段代码

– NetConstructor.com
2010-09-17 6:50

在WordPress 3.0.1中,此过滤器的优先级为11,因此您需要添加11作为第三个参数将其删除。

– Jan Fabry
2010-11-5 23:01

#11 楼

自定义仪表板

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');

function my_custom_dashboard_widgets() {
   global $wp_meta_boxes;


删除这些仪表板小部件...

   unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
   unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
   unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);


添加名为“帮助和支持'

   wp_add_dashboard_widget('custom_help_widget', 'Help and Support', 'custom_dashboard_help');
}


这是您的自定义小部件的内容

 function custom_dashboard_help() {
    echo '<p>Lorum ipsum delor sit amet et nunc</p>';
}


#12 楼

添加自定义用户配置文件字段
将以下代码放入您的functions.php文件中,以添加自定义用户配置文件字段。
请记住不要删除该行:return $ contactmethods;
// CUSTOM USER PROFILE FIELDS
   function my_custom_userfields( $contactmethods ) {

    // ADD CONTACT CUSTOM FIELDS
    $contactmethods['contact_phone_office']     = 'Office Phone';
    $contactmethods['contact_phone_mobile']     = 'Mobile Phone';
    $contactmethods['contact_office_fax']       = 'Office Fax';

    // ADD ADDRESS CUSTOM FIELDS
    $contactmethods['address_line_1']       = 'Address Line 1';
    $contactmethods['address_line_2']       = 'Address Line 2 (optional)';
    $contactmethods['address_city']         = 'City';
    $contactmethods['address_state']        = 'State';
    $contactmethods['address_zipcode']      = 'Zipcode';
    return $contactmethods;
   }
   add_filter('user_contactmethods','my_custom_userfields',10,1);

要显示自定义字段,可以使用下面列出的两种方法之一。
选项1:
the_author_meta('facebook', $current_author->ID)

选项2:
<?php $current_author = get_userdata(get_query_var('author')); ?>
<p><a href="<?php echo esc_url($current_author->contact_phone_office);?>" title="office_phone"> Office Phone</a></p>


#13 楼

更改摘录长度的功能
测试于:Wordpress 3.0.1
默认情况下,所有摘录的上限均为55个单词。使用下面的代码,您可以覆盖此默认设置:
function new_excerpt_length($length) { 
    return 100;
}

add_filter('excerpt_length', 'new_excerpt_length');

本示例将摘录长度更改为100个字,但是您可以使用相同的方法将其更改为任何值。

评论


@ user402 ...是否用文字或字符限制?您可以张贴两者的用法吗?

– NetConstructor.com
2010-09-12 9:14

@ NetConstructor.com此函数(和excerpt_length钩子)由单词限制。

–EAMann
2010-09-15 17:53



嘿。我将过滤器添加到核心。 :)

–道格拉斯·坎贝尔
2011-3-8在19:22

#14 楼

自定义管理菜单的顺序
在WordPress 3.0.1上进行了测试
该代码将允许您重新组织管理菜单中元素的顺序。您需要做的就是单击管理菜单中的现有链接,然后复制/ wp-admin / URL之前的所有内容。下面的顺序代表新管理菜单的顺序。
// CUSTOMIZE ADMIN MENU ORDER
function custom_menu_order($menu_ord) {
    if (!$menu_ord)
        return true;
    return array(
     'index.php', // This represents the dashboard link
     'edit.php?post_type=events', // This is a custom post type menu
     'edit.php?post_type=news',
     'edit.php?post_type=articles',
     'edit.php?post_type=faqs',
     'edit.php?post_type=mentors',
     'edit.php?post_type=testimonials',
     'edit.php?post_type=services',
     'edit.php?post_type=page', // This is the default page menu
     'edit.php', // This is the default POST admin menu
 );
}
add_filter('custom_menu_order', 'custom_menu_order');
add_filter('menu_order', 'custom_menu_order');


评论


是否真的有一个名为custom_menu_order的核心过滤器?我找不到一个...

– kaiser
2011年3月1日于16:55

@kaiser此处记录为codex.wordpress.org/Plugin_API/Filter_Reference/…

–曼妮·弗勒蒙德(Manny Fleurmond)
2012年8月18日在17:08

#15 楼

在“管理帖子/页面”列表中添加缩略图
您可以将其添加到您的功能中,以显示到“管理/编辑帖子和页面”列表中并带有缩略图预览的新列。
/****** Add Thumbnails in Manage Posts/Pages List ******/
if ( !function_exists('AddThumbColumn') && function_exists('add_theme_support') ) {
 
    // for post and page
    add_theme_support('post-thumbnails', array( 'post', 'page' ) );
 
    function AddThumbColumn($cols) {
 
        $cols['thumbnail'] = __('Thumbnail');
 
        return $cols;
    }
 
    function AddThumbValue($column_name, $post_id) {
 
            $width = (int) 35;
            $height = (int) 35;
 
            if ( 'thumbnail' == $column_name ) {
                // thumbnail of WP 2.9
                $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
                // image from gallery
                $attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') );
                if ($thumbnail_id)
                    $thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
                elseif ($attachments) {
                    foreach ( $attachments as $attachment_id => $attachment ) {
                        $thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
                    }
                }
                    if ( isset($thumb) && $thumb ) {
                        echo $thumb;
                    } else {
                        echo __('None');
                    }
            }
    }
 
    // for posts
    add_filter( 'manage_posts_columns', 'AddThumbColumn' );
    add_action( 'manage_posts_custom_column', 'AddThumbValue', 10, 2 );
 
    // for pages
    add_filter( 'manage_pages_columns', 'AddThumbColumn' );
    add_action( 'manage_pages_custom_column', 'AddThumbValue', 10, 2 );
}


评论


如何将列移到最左边?

–丰富
13年10月8日在17:10

#16 楼

将ping删除到自己的博客中
在WordPress 3.0.1上进行了测试
// Remove pings to self
function no_self_ping( &$links ) {
    $home = get_option( 'home' );
    foreach ( $links as $l => $link )
        if ( 0 === strpos( $link, $home ) )
            unset($links[$l]);
}
add_action( 'pre_ping', 'no_self_ping' );


评论


wordpress会多久检查一次自己?

– NetConstructor.com
2010-09-17 6:54

实际上,我经常遇到这个问题。如果我在WP博客上引用了指向另一篇文章的内部链接,我自己会得到引用或pingback(不记得是哪个)。这很烦人。

– Sahas Katta
2010-12-18 23:12

同样在这里。我有一个新闻/杂志博客,并经常链接到其他文章。

–史蒂文
2011-2-13在13:24

#17 楼

启用GZIP输出压缩

通常应将服务器设置为自动执行此操作,但是许多共享主机不执行此操作(可能会增加客户端带宽使用率)。

 if(extension_loaded("zlib") && (ini_get("output_handler") != "ob_gzhandler"))
   add_action('wp', create_function('', '@ob_end_clean();@ini_set("zlib.output_compression", 1);'));


#18 楼

显示数据库查询,花费的时间和内存消耗
在WordPress 3.0.1上进行了测试
function performance( $visible = false ) {

    $stat = sprintf( '%d queries in %.3f seconds, using %.2fMB memory',
            get_num_queries(),
            timer_stop( 0, 3 ),
            memory_get_peak_usage() / 1024 / 1024
        );

    echo $visible ? $stat : "<!-- {$stat} -->" ;
}

然后在上面的代码下面的这段代码将上面的代码自动插入到您的公共网站的页脚中(确保您的主题正在调用wp_footer):
add_action( 'wp_footer', 'performance', 20 );

可以多次调用。

评论


对于php <5.2,请使用memory_get_usage()

–onetrickpony
2011年1月23日在8:23

#19 楼

取消注册WordPress默认小部件
测试于:WordPress 3.0.1
// Unregister all default WordPress Widgets
function unregister_default_wp_widgets() {
    unregister_widget('WP_Widget_Pages');
    unregister_widget('WP_Widget_Calendar');
    unregister_widget('WP_Widget_Archives');
    unregister_widget('WP_Widget_Links');
    unregister_widget('WP_Widget_Meta');
    unregister_widget('WP_Widget_Search');
    unregister_widget('WP_Widget_Text');
    unregister_widget('WP_Widget_Categories');
    unregister_widget('WP_Widget_Recent_Posts');
    unregister_widget('WP_Widget_Recent_Comments');
    unregister_widget('WP_Widget_RSS');
    unregister_widget('WP_Widget_Tag_Cloud');
}
add_action('widgets_init', 'unregister_default_wp_widgets', 1);


评论


我在版本3.1.4上使用过它。但是小部件仍然存在。有人有主意吗?

–user391
2011年7月1日14:22

仍适用于WP 4.5 :)

–蒂姆·马隆(Tim Malone)
16-4-19的3:26

#20 楼

自动从帖子内容中提取第一张图片
在WordPress 3.0.1上进行了测试
此代码将自动提取与帖子关联的第一张图片,并允许您通过调用getImage函数来显示/使用它。
// AUTOMATICALLY EXTRACT THE FIRST IMAGE FROM THE POST
function getImage($num) {
    global $more;
    $more = 1;
    $link = get_permalink();
    $content = get_the_content();
    $count = substr_count($content, '<img');
    $start = 0;

    for($i=1;$i<=$count;$i++) {
        $imgBeg = strpos($content, '<img', $start);
        $post = substr($content, $imgBeg);
        $imgEnd = strpos($post, '>');
        $postOutput = substr($post, 0, $imgEnd+1);
        $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
        $image[$i] = $postOutput;
        $start=$imgEnd+1;
    }

    if(stristr($image[$num],'<img')) {
        echo '<a href="'.$link.'">'.$image[$num]."</a>";
    }
    $more = 0;
}


评论


很好,但是get_the_image对此也做得很好。 wordpress.org/extend/plugins/获取图片

– artlung
2010-09-15 15:56

正确,但是此方法的工作方式不同,并修复了get_the_image未考虑的各种问题

– NetConstructor.com
2010-09-30 11:19

它与get_the_image脚本有什么不同?

–马特
2010-12-05 4:47

@matt-在wordpress中,可以通过多种方式将图像添加到帖子中,我认为get_the_image脚本只是其中一种。这将检查是否有特色图像,如果可用,则首先使用该图像,然后我认为它会检查添加到帖子内容中的第一个图像,如果找不到,则会检查媒体库中排序最高的图像订单(至少这就是我记得订单进行的方式)。

– NetConstructor.com
2011-2-22在20:01

我建议wordpress.org/extend/plugins/auto-post-thumbnail仅在未设置“发布缩略图”的情况下,根据帖子中的第一张图片或任何自定义帖子类型自动生成“发布缩略图”(功能缩略图)

–Ünsal Korkmaz
2011年5月8日12:47

#21 楼

在标题中输出帖子/页面正在使用哪个主题模板文件

add_action('wp_head', 'show_template');
function show_template() {
    global $template;
    print_r($template);
}


如果主题正在使用post_class,则缩短默认的DIV输出。

如果您的主题使用的是类似

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>


您的源代码中可能会有疯狂的长div,看起来可能像这样甚至更长: >
<div id="post-4" class="post-4 post type-post hentry category-uncategorized category-test category-test-1-billion category-test2 category-test3 category-testing">


在大多数情况下,这确实会开始使您的源变得混乱,并且似乎是不必要的,将3-4英寸深就足够了。像这样的输出:

// Slice crazy long div outputs
function category_id_class($classes) {
    global $post;
    foreach((get_the_category($post->ID)) as $category)
        $classes[] = $category->category_nicename;
        return array_slice($classes, 0,5);
}
add_filter('post_class', 'category_id_class');


这将输出切成仅包括前5个值,因此上面的示例变为: br />
使类别档案显示所有帖子,无论帖子类型如何:适用于自定义帖子类型

<div id="post-4" class="post-4 post type-post hentry category-uncategorized">


删除不需要的仪表板项目

它已经发布了,但是没有完整的项目列表。尤其是那些烦人的“传入链接”。

function any_ptype_on_cat($request) {

    if ( isset($request['category_name']) )
        $request['post_type'] = 'any';

    return $request;
}
add_filter('request', 'any_ptype_on_cat');


删除“阅读更多”页面会跳转**

而不是返回页面顶部。您知道如何单击“阅读更多”,它会跳到页面上令人讨厌的位置,这使它仅加载页面即可,没有跳跃!

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');

function my_custom_dashboard_widgets() {
    global $wp_meta_boxes;

    // Right Now - Comments, Posts, Pages at a glance
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);

    // Recent Comments
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);

    // Incoming Links
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);

    // Plugins - Popular, New and Recently updated Wordpress Plugins
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);

    // WordPress Development Blog Feed
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);

    // Other WordPress News Feed
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);

    // Quick Press Form
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);

    // Recent Drafts List
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']);
}



基于用户名限制ADMIN菜单项,将用户名替换为实际用户名。

-> user_login!='admin'),可能更有用

标记云的样式

function remove_more_jump_link($link) {
    $offset = strpos($link, '#more-');
    if ($offset) {
        $end = strpos($link, '"', $offset);
    }
    if ($end) {
        $link = substr_replace($link, '', $offset, $end-$offset);
    }
    return $link;
}
add_filter('the_content_more_link', 'remove_more_jump_link');


选项的完整参考在这里(有很多!)http://codex.wordpress.org/Function_Reference/wp_tag_cloud

更改默认的RSS Widget更新计时器

(默认为6或12个小时-我忘了(1800 = 30分钟)。

function remove_menus()
{
    global $menu;
    global $current_user;
    get_currentuserinfo();

    if($current_user->user_login == 'username')
    {
        $restricted = array(__('Posts'),
                            __('Media'),
                            __('Links'),
                            __('Pages'),
                            __('Comments'),
                            __('Appearance'),
                            __('Plugins'),
                            __('Users'),
                            __('Tools'),
                            __('Settings')
        );
        end ($menu);
        while (prev($menu)) {
            $value = explode(' ',$menu[key($menu)][0]);
            if(in_array($value[0] != NULL ? $value[0] : "" , $restricted)) {
                unset($menu[key($menu)]);
            }
        } // end while

    } // end if
}
add_action('admin_menu', 'remove_menus');


评论


您能否在接下来的几周内将每个答案分解成单独的答案。我本来打算为您做的,但是不想让我觉得您的回答值得赞扬。无论如何-我试图将其整理得井井有条,以便用户可以轻松地找到他们想要的信息。提前致谢

– NetConstructor.com
2011-1-26 14:25

我只是在使用代码“基于用户名限制ADMIN菜单项,用实际的用户名替换用户名”,这很棒,但是您可以更新代码以显示如何针对特定的“用户角色”进行操作。我认为这将非常有用!

– NetConstructor.com
2011-2-22在20:13

抱歉,NetConstructor我刚刚看到您的评论。对于用户角色,我将使用“ current_user_can”。我没有时间对其进行测试,但是当我进行测试时,我将添加它。

–维克
2011-3-4在3:47

wp_feed_cache_transient_lifetime的默认值为43200(12小时)

–brasofilo
2012年4月2日在22:15

#22 楼

删除仅针对无效插件的插件更新通知
function update_active_plugins($value = '') {
    /*
    The $value array passed in contains the list of plugins with time
    marks when the last time the groups was checked for version match
    The $value->reponse node contains an array of the items that are
    out of date. This response node is use by the 'Plugins' menu
    for example to indicate there are updates. Also on the actual
    plugins listing to provide the yellow box below a given plugin
    to indicate action is needed by the user.
    */
    if ((isset($value->response)) && (count($value->response))) {

        // Get the list cut current active plugins
        $active_plugins = get_option('active_plugins');    
        if ($active_plugins) {
           
            //  Here we start to compare the $value->response
            //  items checking each against the active plugins list.
            foreach($value->response as $plugin_idx => $plugin_item) {

                // If the response item is not an active plugin then remove it.
                // This will prevent WordPress from indicating the plugin needs update actions.
                if (!in_array($plugin_idx, $active_plugins))
                    unset($value->response[$plugin_idx]);
            }
        }
        else {
             // If no active plugins then ignore the inactive out of date ones.
            foreach($value->response as $plugin_idx => $plugin_item) {
                unset($value->response);
            }          
        }
    }  
    return $value;
}
add_filter('transient_update_plugins', 'update_active_plugins');    // Hook for 2.8.+
//add_filter( 'option_update_plugins', 'update_active_plugins');    // Hook for 2.7.x


评论


这不一定是一个好主意-文件系统中仍然存在不活动的插件,仍然可以利用不安全的插件来入侵该网站。插件应始终保持最新。

–蒂姆·马隆(Tim Malone)
16年4月11日在20:45

#23 楼

删除<head>标签内的多余信息和HTML
// remove unnecessary header info
add_action( 'init', 'remove_header_info' );
function remove_header_info() {
    remove_action( 'wp_head', 'rsd_link' );
    remove_action( 'wp_head', 'wlwmanifest_link' );
    remove_action( 'wp_head', 'wp_generator' );
    remove_action( 'wp_head', 'start_post_rel_link' );
    remove_action( 'wp_head', 'index_rel_link' );
    remove_action( 'wp_head', 'adjacent_posts_rel_link' );         // for WordPress < 3.0
    remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head' ); // for WordPress >= 3.0
}

// remove extra CSS that 'Recent Comments' widget injects
add_action( 'widgets_init', 'remove_recent_comments_style' );
function remove_recent_comments_style() {
    global $wp_widget_factory;
    remove_action( 'wp_head', array(
        $wp_widget_factory->widgets['WP_Widget_Recent_Comments'],
        'recent_comments_style'
    ) );
}


#24 楼

启用错误调试和日志记录以在实时站点上使用

这是我编写的一段代码,利用WP_DEBUG常量(通常默认情况下禁用)。好吧,我创建了一种方法,不仅可以启用WP_DEBUG,以便可以在没有负面副作用的实时站点上使用它,而且还利用了其他调试常量来强制显示错误并创建日志文件/ wp-content目录中的错误和注意事项。

将此代码拖放到wp-config.php文件中(在仅保存备份的情况下),然后可以传递?debug = 1、2或3个参数,位于您网站上任何URL的末尾。

?debug = 1 =显示所有错误/通知
?debug = 2 =强制显示它们
?debug = 3 =在/ wp-content目录中创建一个包含所有错误的debug.log文件。

/**
* Written by Jared Williams - http://new2wp.com
* @wp-config.php replace WP_DEBUG constant with this code
* Enable WP debugging for usage on a live site
* http://core.trac.wordpress.org/browser/trunk/wp-includes/load.php#L230
* Pass the '?debug=#' parameter at the end of any URL on site
*
* http://example.com/?debug=1, /?debug=2, /?debug=3
*/
if ( isset($_GET['debug']) && $_GET['debug'] == '1' ) {
    // Enable the reporting of notices during development - E_ALL
    define('WP_DEBUG', true);
} elseif ( isset($_GET['debug']) && $_GET['debug'] == '2' ) {
    // Must be true for WP_DEBUG_DISPLAY to work
    define('WP_DEBUG', true);
    // Force the display of errors
    define('WP_DEBUG_DISPLAY', true);
} elseif ( isset($_GET['debug']) && $_GET['debug'] == '3' ) {
    // Must be true for WP_DEBUG_LOG to work
    define('WP_DEBUG', true);
    // Log errors to debug.log in the wp-content directory
    define('WP_DEBUG_LOG', true);
}


我将在来宾上详细介绍如果您有兴趣,我为Comluv撰写的帖子,位于:
http://comluv.com/dev/enable-debugging-and-logging-for-live-site-usage/

我仍在设法使该密码受保护,或者最好以某种方式使其在if(current_user_can('manage_themes')和is_logg ed_in()。

但是那儿要棘手得多。

评论


我们使用类似于设置实时,暂存和开发数据库连接详细信息的方法。

–汤姆
2011-3-7在17:14

#25 楼

新角色和功能-只能运行一次!

我很方便使用这些,这是无需插件即可正确完成操作的正确方法。它们在选项数据库中设置了一个字段(prefix_user_roles),并且您不需要插件即可设置它们。有关可用功能及其功能说明的列表,请参见“法典”页面。您只需要取消注释这些块之一,加载任何页面,然后再次对其进行注释即可!在这里,我正在创建具有所需功能的角色:

/* Capabilities */

// To add the new role, using 'international' as the short name and
// 'International Blogger' as the displayed name in the User list and edit page:
/*
add_role('international', 'International Blogger', array(
    'read' => true, // True allows that capability, False specifically removes it.
    'edit_posts' => true,
    'delete_posts' => true,
    'edit_published_posts' => true,
    'publish_posts' => true,
    'edit_files' => true,
    'import' => true,
    'upload_files' => true //last in array needs no comma!
));
*/


// To remove one outright or remove one of the defaults:
/* 
remove_role('international');
*/


从现有角色中添加/删除有时比删除和重新添加一个角色更方便。同样,您只需要取消注释,重新加载页面,然后再次对其进行评论即可。这会将角色/功能正确存储在选项表中。 (这使开发人员可以控制它们,并消除了执行相同操作的笨重插件的开销。)在这里,我正在更改作者角色以删除其已发布的帖子(默认设置),但允许他们进行编辑他们发布的帖子(默认情况下,此角色是不可能的)-使用* add_cap *或* remove_cap *。

/*
$edit_role = get_role('author');
   $edit_role->add_cap('edit_published_posts');
   $edit_role->remove_cap('delete_published_posts');
*/


我保存了法典页面上带有表格的网格电子表格,以便于以这种方式进行修改的网站,尽管留下了注释掉的代码,但我仍记得设置方式在functions.php文件中将起作用。请不要对这些示例进行注释,否则它将在每次页面加载时写入数据库!

评论


我上面提到的功能写入选项数据库中的字段。评论和取消评论是要走的路。有一些用于用户角色的插件,但是如果您使用上面提到的功能,则不能使这些功能保持运行状态,并且不需要多次设置它们,也不必根据特定用户是否正在访问某些内容来进行设置。如果需要,请为该用户设置特定的,唯一的角色。并参考法典,如果没有插件,我在上面编写的所有内容都是100%正确的。对于几乎每种情况,您只需要设置一次用户角色。

–tomcat23
2011年2月2日在8:58

@ tomcat23:为说明起见,我将其包装在一个函数中,仅当该角色不存在时才添加该角色。另一个注意事项:我认为将角色放置在角色层次结构中的某个位置会更容易,方法是从某些内置角色中获取上限,然后从内置角色中添加/删除功能。如果将它们的瓶盖放在ex之间的某个位置,将使它更清晰,更容易记住。管理员和编辑。 -希望您不要介意我编辑了您的答案。如果您这样做,请重新扮演角色。 :)

– kaiser
2011年3月1日在16:25



@ tomcat23-此时在桥下的水。我要说的是,我对责备不感兴趣,只是对每个前进的人都感到和平。 :)

– MikeSchinkel
2011年3月13日在6:55



@MikeSchinkel是的,您是对的。 @kaiser我很抱歉,如果我造成了您的侮辱。

–tomcat23
2011年3月13日在8:08



@MikeSchinkel:感谢您恢复和平。@ tomcat23:不,您没有。我可以应对这种批评。我也道歉。

– kaiser
2011年3月13日在17:44

#26 楼

自动在公共页面上添加动态标题
在WordPress 3.0.1上进行了测试
使用以下代码将根据正在公开查看的页面/帖子自动创建动态页面标题。
/* Dynamic Titles **/
// This sets your <title> depending on what page you're on, for better formatting and for SEO
// You need to set the variable $longd to some custom text at the beginning of the function
function dynamictitles() {
    $longd = __('Enter your longdescription here.', 'texdomainstring');
        if ( is_single() ) {
          wp_title('');
          echo ' | '.get_bloginfo('name');

    } else if ( is_page() || is_paged() ) {
          bloginfo('name');
          wp_title('|');

    } else if ( is_author() ) {
          bloginfo('name');
          wp_title(' | '.__('Author', 'texdomainstring'));

    } else if ( is_category() ) {
          bloginfo('name');
          wp_title(' | '.__('Archive for', 'texdomainstring'));

    } else if ( is_tag() ) {
          echo get_bloginfo('name').' | '.__('Tag archive for', 'texdomainstring');
          wp_title('');

    } else if ( is_archive() ) {
          echo get_bloginfo('name').' | '.__('Archive for', 'texdomainstring');
          wp_title('');

    } else if ( is_search() ) {
          echo get_bloginfo('name').' | '.__('Search Results', 'texdomainstring');
    } else if ( is_404() ) {
          echo get_bloginfo('name').' | '.__('404 Error (Page Not Found)', 'texdomainstring');

    } else if ( is_home() ) {
          echo get_bloginfo('name').' | '.get_bloginfo('description');

    } else {
          echo get_bloginfo('name').' | '.($blog_longd);
    }
}


#27 楼

Wordpress自定义管理员页脚

// customize admin footer text
function custom_admin_footer() {
        echo 'add your custom footer text and html here';
} 
add_filter('admin_footer_text', 'custom_admin_footer');


我将其用作客户站点的简单参考点,以作为开发人员与我联系。

#28 楼

在小部件中启用简码
// shortcode in widgets
if ( !is_admin() ){
    add_filter('widget_text', 'do_shortcode', 11);
}


#29 楼

禁用RSS提要的功能
测试于:Wordpress 3.0.1
如果希望将基于Wordpress的网站保持为静态,则可以禁用RSS提要。
可以使用此功能:
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);


评论


资料来源:bueltge.de/wordpress-feeds-deaktivieren/794(Frank Bueltge)

– fuxia♦
2010-09-16在10:06

感谢Toscho!该来源也可以用英语wpengineer.com/287/disable-wordpress-feed获得

– Bueltge
2010-09-17 8:27

#30 楼

将“ Howdy”消息更改为“ Welcome”

使用此功能,您可以在管理区域的右上角自定义“ Howdy”消息。
此函数利用JQuery更改“ Howdy”消息发送到“ Welcome”。

/****** Customize admin message "Howdy" to "Welcome" ******/
$nohowdy = "Welcome";

if (is_admin()) {
    add_action('init', 'artdev_nohowdy_h');
    add_action('admin_footer', 'artdev_nohowdy_f');
}
// Load jQuery
function artdev_nohowdy_h() {
    wp_enqueue_script('jquery');
}
// Modify
function artdev_nohowdy_f() {
global $nohowdy;
echo <<<JS
<script type="text/javascript">
//<![CDATA[
var nohowdy = "$nohowdy";
jQuery('#user_info p')
    .html(
    jQuery('#user_info p')
        .html()
        .replace(/Howdy/,nohowdy)
    );
//]]>
JS;
}


PHP版本,使用gettext过滤器:

add_filter('gettext', 'change_howdy', 10, 3);

function change_howdy($translated, $text, $domain) {

    if (!is_admin() || 'default' != $domain)
        return $translated;

    if (false !== strpos($translated, 'Howdy'))
        return str_replace('Howdy', 'Welcome', $translated);

    return $translated;
}


评论


难道不能已经在PHP端对此进行了编辑,因此根本无法获得输出?

– hakre
2011-2-14在19:13

当然,在3.0+版本中,它可以正常工作,但是为什么在较旧的版本中却不能呢?检查您使用的其他任何插件是否对此负责。此处的文本替换为JQuery,也许是JQuery插件?

–菲利普
2011-2-14在20:25