您的‘unctions.php’文件的最佳代码集合

时间:2010-09-09 作者:NetConstructor.com

和其他许多正在阅读这篇文章的人一样,我一直在阅读各种博客、论坛和讨论小组,以学习和提高我的WordPress技能。在过去的12个月里,我一直在执行一项任务,通过在我的functions.php 改为文件。

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

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

因此,这篇文章的目的是让读者/管理员/开发人员与我和这里的其他人分享您觉得有用并添加到主题中的任何代码位function.php 文件扩展或增强WordPress,而无需使用插件。

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

我期待着你的回复,当然,只要我找到了,我会不断添加我自己的新发现。

请点击问题或答案左侧的向上箭头,对问题和任何您认为有用的答案进行投票

102 个回复
SO网友:NetConstructor.com

启用隐藏管理功能显示所有站点设置Tested on:

这段代码做了一些很酷的事情。它将向设置菜单添加一个附加选项,并链接到;“所有设置”;这将显示数据库中与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\');

SO网友:NetConstructor.com

修改登录徽标(&M);图像URL链接Tested on:

此代码允许您轻松修改WordPress登录页面徽标以及此徽标的href链接和标题文本。

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>\';
}
EDIT: 如果要使用站点徽标替换登录徽标,可以使用以下内容动态提取该信息(在上测试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;
}

SO网友:jaredwilli

在搜索结果中包括自定义帖子类型

// 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\' );

Add your custom post types to your sites main RSS feed by default.

// 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\' );

Include custom post types in "Right Now" admin dashboard widget

这将包括您的自定义帖子类型以及;“现在”;仪表板小部件。

// ADD CUSTOM POST TYPES TO THE \'RIGHT NOW\' DASHBOARD WIDGET
function wph_right_now_content_table_end() {
 $args = array(
  \'public\' => true ,
  \'_builtin\' => false
 );
 $output = \'object\';
 $operator = \'and\';
 $post_types = get_post_types( $args , $output , $operator );
 foreach( $post_types as $post_type ) {
  $num_posts = wp_count_posts( $post_type->name );
  $num = number_format_i18n( $num_posts->publish );
  $text = _n( $post_type->labels->singular_name, $post_type->labels->name , intval( $num_posts->publish ) );
  if ( current_user_can( \'edit_posts\' ) ) {
   $num = "<a href=\'edit.php?post_type=$post_type->name\'>$num</a>";
   $text = "<a href=\'edit.php?post_type=$post_type->name\'>$text</a>";
  }
  echo \'<tr><td class="first num b b-\' . $post_type->name . \'">\' . $num . \'</td>\';
  echo \'<td class="text t \' . $post_type->name . \'">\' . $text . \'</td></tr>\';
 }
 $taxonomies = get_taxonomies( $args , $output , $operator ); 
 foreach( $taxonomies as $taxonomy ) {
  $num_terms  = wp_count_terms( $taxonomy->name );
  $num = number_format_i18n( $num_terms );
  $text = _n( $taxonomy->labels->singular_name, $taxonomy->labels->name , intval( $num_terms ));
  if ( current_user_can( \'manage_categories\' ) ) {
   $num = "<a href=\'edit-tags.php?taxonomy=$taxonomy->name\'>$num</a>";
   $text = "<a href=\'edit-tags.php?taxonomy=$taxonomy->name\'>$text</a>";
  }
  echo \'<tr><td class="first b b-\' . $taxonomy->name . \'">\' . $num . \'</td>\';
  echo \'<td class="t \' . $taxonomy->name . \'">\' . $text . \'</td></tr>\';
 }
}
add_action( \'right_now_content_table_end\' , \'wph_right_now_content_table_end\' );

SO网友:NetConstructor.com

删除除管理员用户以外的所有用户的更新通知Tested on:

此代码将确保除“之外,没有其他用户”;“管理”;更新可用时由WordPress通知。。

// 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”):

// 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;" ) );
       }

SO网友:Derek Perkins

从Google CDN加载jQuery

Tested on: 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版本信息Tested on: WordPress 3.0.1

// Remove version info from head and feeds
function complete_version_removal() {
    return \'\';
}
add_filter(\'the_generator\', \'complete_version_removal\');
添加垃圾邮件(&H);删除前端评论链接Tested on: 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提要公开发布Tested on: 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\');

SO网友:jerclarke

设置post修订的最大数量,以避免DB膨胀

Tested on:

默认值为无限,这将设置为仅记住最后五次编辑:

/**
 * Set the post revisions unless the constant was set in wp-config.php
 */
if (!defined(\'WP_POST_REVISIONS\')) define(\'WP_POST_REVISIONS\', 5);
值得一提的是,有很多关于常数的好主意可以在Codex页面上设置Editing wp-config.php.

SO网友:Denis de Bernardy

WordPress评测工具我喜欢在单独的文件中添加评测工具,然后从函数中包括这些工具。需要时使用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);
?>

SO网友:Ünsal Korkmaz

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

此函数用于锐化已调整大小的JPEG图像。差异示例:

http://dl.dropbox.com/u/1652601/forrst/gdsharpen.png

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);

SO网友:NetConstructor.com

删除默认WordPress元框Tested on:

此代码允许您删除WordPress默认添加到默认添加/编辑帖子和添加/编辑页面屏幕的特定元框。

// 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\');

SO网友:EAMann

删除“;Wordpress;“至”;WordPress;过滤器Tested on:

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 );
}

SO网友:George Wiscombe

自定义仪表板

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>\';
}

SO网友:NetConstructor.com

添加自定义用户配置文件字段将下面的代码放入函数中。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);
要显示自定义字段,可以使用下面列出的两种方法之一。

Option 1:

the_author_meta(\'facebook\', $current_author->ID)

Option 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>

SO网友:NetConstructor.com

自定义管理菜单的顺序Tested on: 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\');

SO网友:Name-AK

用于更改EXPERT长度的函数Tested on:

默认情况下,所有摘录的字数上限为55个字。使用以下代码,您可以覆盖此默认设置:

function new_excerpt_length($length) { 
    return 100;
}

add_filter(\'excerpt_length\', \'new_excerpt_length\');
本例将摘录长度更改为100个单词,但您可以使用相同的方法将其更改为任何值。

SO网友:Philip

在“管理文章/页面”列表中添加缩略图您可以将其添加到功能中,以便在“管理/编辑文章和页面”列表中显示带有缩略图预览的新列。

/****** 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 );
}

SO网友:Dan Gayle

删除对自己博客的pingTested on:

// 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\' );

SO网友:onetrickpony

启用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);\'));

SO网友:Rarst

显示数据库查询、花费的时间和内存消耗Tested on:

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 );
可以多次调用。

SO网友:NetConstructor.com

自动从帖子内容中提取第一幅图像Tested on:

此代码将自动提取与帖子关联的第一个图像,并允许您通过调用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;
}

SO网友:bueltge

注销WordPress默认窗口小部件Tested on:

// 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);

SO网友:Wyck

输出文章/页面在标题中使用的主题模板文件

add_action(\'wp_head\', \'show_template\');
function show_template() {
    global $template;
    print_r($template);
}
如果主题使用post\\u类,请缩短默认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个值,因此上述示例变为:

<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\']);
}
删除“阅读更多”页面跳转**而返回页面顶部。你知道当你点击“阅读更多”时,它会跳转到页面中令人讨厌的地方,这使得它只能正常加载页面,不能跳转!

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\');

Restrict ADMIN menu items based on username, 将用户名替换为实际用户名

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\');

//alternatively you can use if($current_user->user_login != \'admin\') instead, probably more useful

设置标记云的样式

// Tag cloud custom
add_filter(\'widget_tag_cloud_args\', \'style_tags\');
function style_tags($args) {
    $args = array(
         \'largest\'    => \'10\',
         \'smallest\'   => \'10\',
         \'format\'     => \'list\',
         );
    return $args;
}
这里有完整的选项参考(有很多!)http://codex.wordpress.org/Function_Reference/wp_tag_cloud

更改默认RSS小部件更新计时器(默认为6或12小时-我忘记了(1800=30分钟)。

add_filter( \'wp_feed_cache_transient_lifetime\', create_function(\'$fixrss\', \'return 1800;\') );

SO网友:NetConstructor.com

仅针对非活动插件删除插件更新通知

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

SO网友:jaredwilli

启用实时站点上使用的错误调试和日志记录这是我编写的一段代码,它利用了默认情况下通常禁用的WP\\U调试常量。我创建了一种方法,不仅可以启用WP\\u DEBUG,这样您就可以在实时站点上使用它,而不会产生负面的副作用,而且还可以使用其他调试常量来强制显示错误,并在/WP content目录中创建错误和通知的日志文件。

在wp配置中删除此代码。php文件(保存备份以防万一后),然后可以传递?debug=站点上任何URL末尾的1、2或3个参数。

?调试=1=显示所有错误/通知?调试=2=强制显示?调试=3=创建调试。/wp内容目录中所有错误的日志文件。

/**
* 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\\u user\\u can(\'manage\\u themes\')和is\\u logged\\u in()上工作。

但这就是它变得更加棘手的地方。

SO网友:Chris_O

自动将动态标题添加到公共页面Tested on:

使用下面的代码将根据公开查看的页面/帖子自动创建动态页面标题。

/* 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);
    }
}

SO网友:tomcat23

新角色和功能-仅运行一次

我把这些放在手边,这是不需要插件就可以完成它们的正确方法。它们在选项数据库中设置单个字段(prefix\\u user\\u roles),您不需要插件来设置它们。Refer to the Codex page for a list of what capabilities are available and descriptions for what they do. You only need to uncomment one of these blocks, load any page and then comment them again! 在这里,我要创建一个具备我所需能力的角色:

/* 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\');
*/
有时,从现有角色中添加/删除角色比删除和重新添加角色更方便。Again, you only need to uncomment it, reload a page and then comment it again. 这将在选项表中正确存储角色/功能。(这允许您(开发人员)控制它们,并消除做同样事情的庞大插件的开销。)在这里,我将作者角色更改为删除其发布的帖子(默认),但允许他们编辑其发布的帖子(默认情况下,此角色不可能)——使用*add\\u cap*或*remove\\u cap*。

/*
$edit_role = get_role(\'author\');
   $edit_role->add_cap(\'edit_published_posts\');
   $edit_role->remove_cap(\'delete_published_posts\');
*/
我在Codex页面为以这种方式修改的站点保留了一个带有网格的电子表格,这样我就可以记住事情是如何设置的,尽管在函数中保留了注释掉的代码。php文件将用于。不要让这些示例保持未注释状态,否则它会在每次加载页面时写入数据库!

SO网友:CommentLuv

在小部件中启用短代码

// shortcode in widgets
if ( !is_admin() ){
    add_filter(\'widget_text\', \'do_shortcode\', 11);
}

SO网友:chuck reynolds

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\');
我将此用于客户端站点,作为联系我作为开发人员的简单参考点。

SO网友:Name-AK

用于禁用RSS源的函数Tested on:

如果要将基于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);

SO网友:Philip

Change the "Howdy" message to "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;
}

SO网友:NetConstructor.com

在“中包括自定义帖子类型”;“现在”;管理仪表板

这将包括您的自定义帖子类型以及;“现在”;仪表板小部件。

// ADD CUSTOM POST TYPES TO THE \'RIGHT NOW\' DASHBOARD WIDGET
function wph_right_now_content_table_end() {
 $args = array(
  \'public\' => true ,
  \'show_ui\' => true ,
  \'_builtin\' => false
 );
 $output = \'object\';
 $operator = \'and\';
 
 $post_types = get_post_types( $args , $output , $operator );
 foreach( $post_types as $post_type ) {
  $num_posts = wp_count_posts( $post_type->name );
  $num = number_format_i18n( $num_posts->publish );
  $text = _n( $post_type->labels->singular_name, $post_type->labels->name , intval( $num_posts->publish ) );
  if ( current_user_can( \'edit_posts\' ) ) {
   $num = "<a href=\'edit.php?post_type=$post_type->name\'>$num</a>";
   $text = "<a href=\'edit.php?post_type=$post_type->name\'>$text</a>";
  }
  echo \'<tr><td class="first b b-\' . $post_type->name . \'">\' . $num . \'</td>\';
  echo \'<td class="t \' . $post_type->name . \'">\' . $text . \'</td></tr>\';
 }
 $taxonomies = get_taxonomies( $args , $output , $operator ); 
 foreach( $taxonomies as $taxonomy ) {
  $num_terms  = wp_count_terms( $taxonomy->name );
  $num = number_format_i18n( $num_terms );
  $text = _n( $taxonomy->labels->singular_name, $taxonomy->labels->name , intval( $num_terms ));
  if ( current_user_can( \'manage_categories\' ) ) {
   $num = "<a href=\'edit-tags.php?taxonomy=$taxonomy->name\'>$num</a>";
   $text = "<a href=\'edit-tags.php?taxonomy=$taxonomy->name\'>$text</a>";
  }
  echo \'<tr><td class="first b b-\' . $taxonomy->name . \'">\' . $num . \'</td>\';
  echo \'<td class="t \' . $taxonomy->name . \'">\' . $text . \'</td></tr>\';
 }
}
add_action( \'right_now_content_table_end\' , \'wph_right_now_content_table_end\' );

SO网友:jaredwilli

将codex搜索表单添加到仪表板标题

这是将codex搜索表单添加到仪表板标题的简单方法,位于“快速链接”下拉列表的右上角。

/**
 * ADD WP CODEX SEARCH FORM TO DASHBOARD HEADER
 */
function wp_codex_search_form() {
    echo \'<form target="_blank" method="get" action="http://wordpress.org/search/do-search.php" class="alignright" style="margin: 11px 5px 0;">
        <input type="text" onblur="this.value=(this.value==\\\'\\\') ? \\\'Search the Codex\\\' : this.value;" onfocus="this.value=(this.value==\\\'Search the Codex\\\') ? \\\'\\\' : this.value;" maxlength="150" value="Search the Codex" name="search" class="text"> <input type="submit" value="Go" class="button" />
    </form>\';
}

if( current_user_can( \'manage_plugins\' )) {
// The number 11 needs to be a 10 for this to work!
    add_filter( \'in_admin_header\', \'wp_codex_search_form\', 11 );
}

SO网友:NetConstructor.com

重新附加图像的新媒体库列此代码向媒体库页面添加一个新列,允许您重新附加图像

add_filter("manage_upload_columns", \'upload_columns\');
add_action("manage_media_custom_column", \'media_custom_columns\', 0, 2);

function upload_columns($columns) {
    unset($columns[\'parent\']);
    $columns[\'better_parent\'] = "Parent";
    return $columns;
}
function media_custom_columns($column_name, $id) {
    $post = get_post($id);
    if($column_name != \'better_parent\')
        return;
        if ( $post->post_parent > 0 ) {
            if ( get_post($post->post_parent) ) {
                $title =_draft_or_post_title($post->post_parent);
            }
            ?>
            <strong><a href="<?php echo get_edit_post_link( $post->post_parent ); ?>"><?php echo $title ?></a></strong>, <?php echo get_the_time(__(\'Y/m/d\')); ?>
            <br />
            <a class="hide-if-no-js" onclick="findPosts.open(\'media[]\',\'<?php echo $post->ID ?>\');return false;" href="#the-list"><?php _e(\'Re-Attach\'); ?></a>
            <?php
        } else {
            ?>
            <?php _e(\'(Unattached)\'); ?><br />
            <a class="hide-if-no-js" onclick="findPosts.open(\'media[]\',\'<?php echo $post->ID ?>\');return false;" href="#the-list"><?php _e(\'Attach\'); ?></a>
            <?php
        }
}

SO网友:onetrickpony

使用短代码的主题自定义循环与中的参数相同query_posts. 包装在查询标记之间的内容是模板。

add_shortcode(\'query\', \'shortcode_query\');

function shortcode_query($atts, $content){
  extract(shortcode_atts(array( // a few default values
   \'posts_per_page\' => \'10\',
   \'caller_get_posts\' => 1,
   \'post__not_in\' => get_option(\'sticky_posts\'),
  ), $atts));

  global $post;

  $posts = new WP_Query($atts);
  $output = \'\';
  if ($posts->have_posts())
    while ($posts->have_posts()):
      $posts->the_post();

      // these arguments will be available from inside $content
      $parameters = array(
        \'PERMALINK\' => get_permalink(),
        \'TITLE\' => get_the_title(),
        \'CONTENT\' => get_the_content(),
        \'COMMENT_COUNT\' => $post->comment_count,
        \'CATEGORIES\' => get_the_category_list(\', \'),
        // add here more...
      );

      $finds = $replaces = array();
      foreach($parameters as $find => $replace):
        $finds[] = \'{\'.$find.\'}\';
        $replaces[] = $replace;
      endforeach;
      $output .= str_replace($finds, $replaces, $content);

    endwhile;
  else
    return; // no posts found

  wp_reset_query();
  return html_entity_decode($output);
}

Usage:

[query post_type=page posts_per_page=5]
Listing some pages:    
<h5>{TITLE}</h5>
<div>{CONTENT}</div>
<p><a href="{PERMALINK}">{COMMENT_COUNT} comments</a></p>
[/query]
(将查询5页)

使用短代码在任何地方插入预配置的小部件http://webdesign.anmari.com/shortcode-any-widget)

add_action(\'widgets_init\', \'create_arbitrary_sidebar\');
function create_arbitrary_sidebar(){
  register_sidebar(array(
    \'name\' => __(\'Arbitrary Widgets\'),
    \'id\' => \'arbitrary\',
    \'description\' => sprintf(__(\'Widgets from this area can added into posts/pages using the %1$s or %2$s shortcodes.\'), \'[widget ID]\', \'[widget Name]\'),
    \'before_widget\' => \'<div class="block"><div class="block-content block-%2$s clear-block" id="instance-%1$s">\',
    \'after_widget\' => \'</div></div>\',
    \'before_title\' => \'<h3 class="title">\',
    \'after_title\' => \'</h3>\'
   ));
}

add_action(\'in_widget_form\', \'widget_shortcodes_info\', 10, 3);
function widget_shortcodes_info($widget, $return, $instance){
  if(!is_numeric($widget->number)) return; // wp-save bug :( widget needs to be saved first...

  global $wp_registered_widgets;

  // get the active widgets from all sidebars
  $sidebars_widgets = wp_get_sidebars_widgets();

  // prepare matches
  $matches = array();
  foreach($wp_registered_widgets as $i => $w)
    if($w[\'name\'] == $widget->name) $matches[] = $w[\'id\'];

  // find out the widget position (number)
  $number = 0;
  $is_arbitrary = false;
  if(!empty($sidebars_widgets[\'arbitrary\']))
    foreach($sidebars_widgets[\'arbitrary\'] as $i => $value):
      if(in_array($value, $matches) && !$is_arbitrary) $number = $number +1;
      if($value == $widget->id) $is_arbitrary = true;
    endforeach;

  echo \'<div style="background:#eee; padding: 5px;">To include this widget into your posts or pages use one of the following shortcodes: <br />\';
  echo \'<code>[widget \'.substr(md5($widget->id), 0, 8).\']</code> <br /> <code>[widget "\'.$widget->name.\'"\'.(($number > 1) ? \' number=\'.$number : null).\']</code></div>\';
}

add_shortcode(\'widget\', \'shortcode_widget\');
function shortcode_widget($atts){
  global $wp_registered_widgets, $wp_registered_sidebars;
  extract(shortcode_atts(array(
    \'number\' => false,        // only taken in consideration if the 1st argument is the "Widget Name" (not the hashed ID)
    \'title\' => true,          // show titles?
    \'area\' => \'arbitrary\'     // sidebar to search
  ), $atts));

  // get 1st parameter (assuming this is the target widget id or name)
  if (!empty($atts[0])) $widget = esc_attr($atts[0]); else return;

  $sidebar = esc_attr($area);
  $number = intval($number);

  $callback = false;
  $possible_matches = array();
  $sidebars_widgets = wp_get_sidebars_widgets();
  if((empty($sidebars_widgets[$sidebar]) || empty($wp_registered_widgets)) && (current_user_can(\'edit_themes\')))
    return "no valid active widgets in {$sidebar}";

  // assuming we get the md5 hashed ID
  foreach ($wp_registered_widgets as $i => $w)
    if ($widget == substr(md5($w[\'id\']), 0, 8)):
      $callback = ($w[\'callback\']);
      $widget = $w[\'id\']; // real widget ID

    // compare widget names as well, and build a array with the possible widget matches array
    // (which is used later if ID match fails)
    elseif($widget == $w[\'name\']):
      $possible_matches[] = $w[\'id\'];

    endif;

  // nothing found, assume it\'s the "Widget Name".
  if(!$callback):
    $valid_matches = array();
    foreach($sidebars_widgets[$sidebar] as $i => $w)
      foreach($possible_matches as $id) if($id == $w) $valid_matches[] = $w;

    if(!empty($valid_matches)) $widget = $number ? $valid_matches[$number-1] : $widget = $valid_matches[0];
    if($widget && isset($wp_registered_widgets[$widget][\'callback\'])) $callback = $wp_registered_widgets[$widget][\'callback\'];
  endif;

  // yey. we found it
  if($callback):
    ob_start();

    $params = array_merge(array(array_merge($wp_registered_sidebars[$sidebar], array(\'widget_id\' => $widget, \'widget_name\' => $wp_registered_widgets[$widget][\'name\']))), (array)$wp_registered_widgets[$widget][\'params\']);

    $classname_ = \'\';
    foreach ((array)$wp_registered_widgets[$widget][\'classname\'] as $cn)
      if (is_string($cn)) $classname_ .= \'_\'.$cn; elseif (is_object($cn)) $classname_ .= \'_\'.get_class($cn);
    $classname_ = ltrim($classname_, \'_\');
    $params[0][\'before_widget\'] = sprintf($params[0][\'before_widget\'], $widget, $classname_);
    $params = apply_filters(\'dynamic_sidebar_params\', $params);

    if (is_callable($callback)) call_user_func_array($callback, $params);
    $output = ob_get_clean();

    // remove h3 if title = false
    if(!$title) $output = preg_replace(\'#<h3 class="title">(.*?)</h3>#\', \'\', $output);
    return $output;
  else:
   return "widget instance not found: ".esc_attr($atts[0]);
  endif;
}

Usage:

将一个小部件放到“任意小部件”侧栏中,保存它,您将得到短代码:)

通过短代码获取自定义字段值

add_shortcode(\'field\', \'shortcode_field\');

function shortcode_field($atts){
  extract(shortcode_atts(array(
   \'post_id\' => NULL,
  ), $atts));

  if(!isset($atts[0])) return;
  $field = esc_attr($atts[0]);

  global $post;
  $post_id = (NULL === $post_id) ? $post->ID : $post_id;

  return get_post_meta($post_id, $field, true);
}

Usage:

  • [field "my_key"]
  • [field "my_key" post_id=1]

通过短码获取链接的TinyURL

add_shortcode(\'tinyurl\', \'shortcode_tinyurl\'); 

function shortcode_tinyurl($atts){
  extract(shortcode_atts(array(
   \'url\' => get_permalink(),
   \'title\' => \'\',
   \'rel\' => \'nofollow\'
  ), $atts));
  if(!$title) $title = $url;

  if (FALSE === ($cache = get_transient(\'tinyurl_\'+md5($url)))):
    $cache = wp_remote_retrieve_body(wp_remote_get(\'http://tinyurl.com/api-create.php?url=\'.$url));

    set_transient(\'tinyurl_\'+md5($url), $cache, 60*60*24); // 1 day cache, could be incresed
  endif;

  return \'<a href="\'.esc_url($cache).\'" rel="\'.esc_attr($rel).\'">\'.esc_attr($title).\'</a>\';
}

Usage:

  • [tinyurl]
  • [tinyurl url="http://google.com" title="google"]

SO网友:NetConstructor.com

将编辑器默认设置为WYSIWYG或HTML

function my_default_editor() {
    $r = \'tinymce\'; // html or tinymce
    return $r;
}
add_filter( \'wp_default_editor\', \'my_default_editor\' );

Here is how to remove the HTML Editor

jQuery(document).ready(function($) {
$("#edButtonHTML").remove();
});
UPDATED下面是将默认编辑器设置为HTML的另一种方法

add_filter(\'wp_default_editor\', create_function(\'\', \'return "html";\'));

SO网友:NetConstructor.com

删除作者元数据库/选项(&O);移动到发布MetaBoxTested on:

让我抓狂的事情之一是一个凌乱的Wordpress管理区。我现在总是从一开始就在函数中设置的元素之一。php文件正在删除作者元框和屏幕选项,然后将该选项添加到发布元框中。在我看来,这是有道理的,可以让事情保持干净。这也尊重适用的权限。

为了实现这一目标,只需将以下代码复制并传递到函数中即可。php文件。

如果您觉得有更好的方法,请提出建议。

注意:更新了代码以修复编码问题

// MOVE THE AUTHOR METABOX INTO THE PUBLISH METABOX
add_action( \'admin_menu\', \'remove_author_metabox\' );
add_action( \'post_submitbox_misc_actions\', \'move_author_to_publish_metabox\' );
function remove_author_metabox() {
    remove_meta_box( \'authordiv\', \'post\', \'normal\' );
}
function move_author_to_publish_metabox() {
    global $post_ID;
    $post = get_post( $post_ID );
    echo \'<div id="author" class="misc-pub-section" style="border-top-style:solid; border-top-width:1px; border-top-color:#EEEEEE; border-bottom-width:0px;">Author: \';
    post_author_meta_box( $post );
    echo \'</div>\';
}

SO网友:Joshua Scott

快速确定服务器(&A);环境详细信息

如果您有多台服务器和多个环境,如开发、QA和生产环境,这将非常有用。

对于我的系统,环境由主机名的前3个字母决定,但这可以很容易地更改为适合您需要的任何字符。

add_action( \'admin_notices\', \'report_environment_status\', 3 );

// Report on which server and environment details
function report_environment_status() {
    $server = php_uname(\'n\');
    switch (strtolower(substr($server,0,3))) {
        case \'pXX\':
            $msg = "PRODUCTION";
            break;
        case \'qXX\':
            $msg = "QA";
            break;
        case \'dXX\':
            $msg = "DEVELOPMENT";
            break;
        default :
            $msg = \'UNKNOWN\';
    }
    echo "<div id=\'update-nag\'>";
    echo "<b>You are in the $msg environment. (Server: $server)</b>";
    echo "</div>";
}
这使我避免了多次更新到错误的环境。

您还可以将其转换为插件并通过网络激活,以便所有站点都能收到通知。

SO网友:NetConstructor.com

延长自动注销时间Tested on:

使用下面的代码,您可以延长Cookie的保存时间,从而使登录的用户保持更长的登录时间:

function keep_me_logged_in_for_1_year( $expirein ) {
   return 31556926; // 1 year in seconds
}
add_filter( \'auth_cookie_expiration\', \'keep_me_logged_in_for_1_year\' );

SO网友:bueltge

添加一个“;“设置”;插件列表页面上的插件链接;“设置”;WordPress后端插件页面上的插件链接,方便用户使用跳转到设置(该代码还提供了WordPress版本2.9的解决方案)

// plugin definitions
define( \'FB_BASENAME\', plugin_basename( __FILE__ ) );
define( \'FB_BASEFOLDER\', plugin_basename( dirname( __FILE__ ) ) );
define( \'FB_FILENAME\', str_replace( FB_BASEFOLDER.\'/\', \'\', plugin_basename(__FILE__) ) );
function filter_plugin_meta($links, $file) {
  /* create link */
  if ( $file == FB_BASENAME ) {
    array_unshift(
      $links,
      sprintf( \'<a href="options-general.php?page=%s">%s</a>\', FB_FILENAME, __(\'Settings\') )
    );
  }
  return $links;
}

global $wp_version;
if ( version_compare( $wp_version, \'2.7alpha\', \'>\' ) ) {
    add_filter( \'plugin_action_links_\' . FB_WM_BASENAME, \'filter_plugin_meta\', 10, 2);
} else {
    add_filter( \'plugin_action_links\', \'filter_plugin_meta\', 10, 2 );
}

SO网友:chuck reynolds

删除WordPress注释中URL的自动链接

remove_filter(\'comment_text\', \'make_clickable\', 9);

SO网友:t31os

将页面模板筛选器添加到页面列表Tested on: WP 3.1

将页面模板筛选器添加到页面列表中,以便查看附加了给定模板的页面列表。

class Page_Template_Filter {
    private $templates = array();
    public function __construct() {
        // If it\'s not the admin area or the current user can\'t edit pages let\'s just bail here
        if( !is_admin() || !current_user_can(\'edit_pages\') )
            return;
        add_action( \'parse_query\',           array( $this, \'pt_parse_query\' ) );
        add_action( \'restrict_manage_posts\', array( $this, \'pt_restrict_manage_posts\' ) );
    }
    public function pt_parse_query( $query ) {
        global $pagenow, $post_type;
        if( \'edit.php\' != $pagenow )
            return;

        switch( $post_type ) {
            case \'post\':

            break;
            case \'page\':
                $this->templates = get_page_templates();

                if( empty( $this->templates ) )
                    return;

                if( !$this->is_set_template() )
                    return;

                $meta_group = array( \'key\' => \'_wp_page_template\', \'value\' => $this->get_template() );
                set_query_var( \'meta_query\', array( $meta_group ) );
            break;
        }
    }
    public function pt_restrict_manage_posts() {
        if( empty( $this->templates ) )
            return;
        $this->template_dropdown();
    }
    private function get_template() {
        if( $this->is_set_template() )
            foreach( $this->templates as $template ) {
                if( $template != $_GET[\'page_template\'] )
                    continue;
                return $template;
            }
        return \'\';
    }
    private function is_set_template() {
        return (bool) ( isset( $_GET[\'page_template\'] ) && ( in_array( $_GET[\'page_template\'], $this->templates ) ) );
    }
    private function template_dropdown() {
        ?>
        <select name="page_template" id="page_template">
            <option value=""> - no template - </option>
            <?php foreach( $this->templates as $name => $file ): ?>
            <option value="<?php echo $file; ?>"<?php selected( $this->get_template() == $file ); ?>><?php _e( $name ); ?></option>
            <?php endforeach;?>
        </select>
        <?php 
    }
}

add_action(\'admin_init\', \'load_ptf\');
function load_ptf() {
    $Page_Template_Filter = new Page_Template_Filter;
}
至少需要3.1才能工作meta_query 可以替换为旧的meta_keymeta_value 对于3.0。

SO网友:Paul

仅显示登录作者的帖子和媒体(&M);固定过滤条上的贴子/介质计数

Tested on:

默认情况下,WordPress允许作者查看其他用户帖子、未发布草稿和所有媒体的标题,即使这些标题无法编辑。

使用此代码仅允许显示当前登录作者的帖子和媒体。

与其他解决方案不同,这还修复了过滤栏上的帖子/媒体计数(所有|已发布|草稿|待定|垃圾;所有|图像|视频|未附加)。

// Show only posts and media related to logged in author
add_action(\'pre_get_posts\', \'query_set_only_author\' );
function query_set_only_author( $wp_query ) {
    global $current_user;
    if( is_admin() && !current_user_can(\'edit_others_posts\') ) {
        $wp_query->set( \'author\', $current_user->ID );
        add_filter(\'views_edit-post\', \'fix_post_counts\');
        add_filter(\'views_upload\', \'fix_media_counts\');
    }
}

// Fix post counts
function fix_post_counts($views) {
    global $current_user, $wp_query;
    unset($views[\'mine\']);
    $types = array(
        array( \'status\' =>  NULL ),
        array( \'status\' => \'publish\' ),
        array( \'status\' => \'draft\' ),
        array( \'status\' => \'pending\' ),
        array( \'status\' => \'trash\' )
    );
    foreach( $types as $type ) {
        $query = array(
            \'author\'      => $current_user->ID,
            \'post_type\'   => \'post\',
            \'post_status\' => $type[\'status\']
        );
        $result = new WP_Query($query);
        if( $type[\'status\'] == NULL ):
            $class = ($wp_query->query_vars[\'post_status\'] == NULL) ? \' class="current"\' : \'\';
            $views[\'all\'] = sprintf(__(\'<a href="%s"\'. $class .\'>All <span class="count">(%d)</span></a>\', \'all\'),
                admin_url(\'edit.php?post_type=post\'),
                $result->found_posts);
        elseif( $type[\'status\'] == \'publish\' ):
            $class = ($wp_query->query_vars[\'post_status\'] == \'publish\') ? \' class="current"\' : \'\';
            $views[\'publish\'] = sprintf(__(\'<a href="%s"\'. $class .\'>Published <span class="count">(%d)</span></a>\', \'publish\'),
                admin_url(\'edit.php?post_status=publish&post_type=post\'),
                $result->found_posts);
        elseif( $type[\'status\'] == \'draft\' ):
            $class = ($wp_query->query_vars[\'post_status\'] == \'draft\') ? \' class="current"\' : \'\';
            $views[\'draft\'] = sprintf(__(\'<a href="%s"\'. $class .\'>Draft\'. ((sizeof($result->posts) > 1) ? "s" : "") .\' <span class="count">(%d)</span></a>\', \'draft\'),
                admin_url(\'edit.php?post_status=draft&post_type=post\'),
                $result->found_posts);
        elseif( $type[\'status\'] == \'pending\' ):
            $class = ($wp_query->query_vars[\'post_status\'] == \'pending\') ? \' class="current"\' : \'\';
            $views[\'pending\'] = sprintf(__(\'<a href="%s"\'. $class .\'>Pending <span class="count">(%d)</span></a>\', \'pending\'),
                admin_url(\'edit.php?post_status=pending&post_type=post\'),
                $result->found_posts);
        elseif( $type[\'status\'] == \'trash\' ):
            $class = ($wp_query->query_vars[\'post_status\'] == \'trash\') ? \' class="current"\' : \'\';
            $views[\'trash\'] = sprintf(__(\'<a href="%s"\'. $class .\'>Trash <span class="count">(%d)</span></a>\', \'trash\'),
                admin_url(\'edit.php?post_status=trash&post_type=post\'),
                $result->found_posts);
        endif;
    }
    return $views;
}

// Fix media counts
function fix_media_counts($views) {
    global $wpdb, $current_user, $post_mime_types, $avail_post_mime_types;
    $views = array();
    $_num_posts = array();
    $count = $wpdb->get_results( "
        SELECT post_mime_type, COUNT( * ) AS num_posts 
        FROM $wpdb->posts 
        WHERE post_type = \'attachment\' 
        AND post_author = $current_user->ID 
        AND post_status != \'trash\' 
        GROUP BY post_mime_type
    ", ARRAY_A );
    foreach( $count as $row )
        $_num_posts[$row[\'post_mime_type\']] = $row[\'num_posts\'];
    $_total_posts = array_sum($_num_posts);
    $detached = isset( $_REQUEST[\'detached\'] ) || isset( $_REQUEST[\'find_detached\'] );
    if ( !isset( $total_orphans ) )
        $total_orphans = $wpdb->get_var("
            SELECT COUNT( * ) 
            FROM $wpdb->posts 
            WHERE post_type = \'attachment\' 
            AND post_author = $current_user->ID 
            AND post_status != \'trash\' 
            AND post_parent < 1
        ");
    $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
    foreach ( $matches as $type => $reals )
        foreach ( $reals as $real )
            $num_posts[$type] = ( isset( $num_posts[$type] ) ) ? $num_posts[$type] + $_num_posts[$real] : $_num_posts[$real];
    $class = ( empty($_GET[\'post_mime_type\']) && !$detached && !isset($_GET[\'status\']) ) ? \' class="current"\' : \'\';
    $views[\'all\'] = "<a href=\'upload.php\'$class>" . sprintf( __(\'All <span class="count">(%s)</span>\', \'uploaded files\' ), number_format_i18n( $_total_posts )) . \'</a>\';
    foreach ( $post_mime_types as $mime_type => $label ) {
        $class = \'\';
        if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) )
            continue;
        if ( !empty($_GET[\'post_mime_type\']) && wp_match_mime_types($mime_type, $_GET[\'post_mime_type\']) )
            $class = \' class="current"\';
        if ( !empty( $num_posts[$mime_type] ) )
            $views[$mime_type] = "<a href=\'upload.php?post_mime_type=$mime_type\'$class>" . sprintf( translate_nooped_plural( $label[2], $num_posts[$mime_type] ), $num_posts[$mime_type] ) . \'</a>\';
    }
    $views[\'detached\'] = \'<a href="upload.php?detached=1"\' . ( $detached ? \' class="current"\' : \'\' ) . \'>\' . sprintf( __( \'Unattached <span class="count">(%s)</span>\', \'detached files\' ), $total_orphans ) . \'</a>\';
    return $views;
}

SO网友:gabrielk

不用于性能提升时删除XML-RPCTested on:

WordPress使用CURL操作来测试XML-RPC的SSL功能。如果您正在使用XML-RPC,但未使用,则可以删除筛选器。这是一个小的性能提升(因为基本上WP在https url上执行cURL GET,1)获取拒绝消息,或2)超时,可能需要5秒钟以上),但在我们的示例中,它实际上阻止了网关超时,其中代理在cURL GET超时之前超时,导致XML-RPC不可用。

// Prevents WordPress from testing ssl capability on domain.com/xmlrpc.php?rsd
remove_filter(\'atom_service_url\',\'atom_service_url_filter\');

SO网友:Sahas Katta

快速功能集合。php编辑我在functions.php 也多年来通过搜索找到了其中的大部分。

Excerpt Ending

function new_excerpt_more($more) {
    return \'...\';
}
add_filter(\'excerpt_more\', \'new_excerpt_more\');

Replace WP Admin Logo

function new_admin_logo() {
  echo \'<style type="text/css">#header-logo { background-image: url(\'.get_bloginfo(\'template_directory\').\'/images/admin_logo.png) !important; }</style>\';
}
add_action(\'admin_head\', \'new_admin_logo\');

Custom Favicon WP-Admin

function admin_favicon() {
 echo \'<link rel="shortcut icon" type="image/x-icon" href="\' . get_bloginfo(\'template_directory\') . \'/images/favicon.ico" />\';
}
add_action( \'admin_head\', \'admin_favicon\' );

Custom Admin Footer

function custom_admin_footer() {
echo \'Welcome to my blog! No More Documentation Links!\';
}
add_filter(\'admin_footer_text\', \'custom_admin_footer\');

SO网友:Norcross

全局获取所有自定义字段

function get_custom_field($key, $echo = FALSE) {
    global $post;
    $custom_field = get_post_meta( $post->ID, $key, true );
    if ( $echo == false ) 
        return $custom_field;
    echo $custom_field;
}

Then call the field with a single line

<?php get_custom_field(\'custom-field-name\', TRUE); ?>

SO网友:superUntitled

返回注释数,如下所示count_user_posts(), 但返回注释数:

function count_user_comments($id) {
global $wpdb;
$users = $wpdb->get_var("
        SELECT COUNT( * ) AS total
        FROM $wpdb->comments
        WHERE comment_approved = 1 
        AND user_id = $id");
return $users;
}

More: Count User\'s posts (including custom post types) or comments:

function atom_count($user_id, $what_to_count = \'post\') {
  global $wpdb;    
  $where = $what_to_count == \'comment\' ? "WHERE comment_approved = 1 AND user_id = {$user_id}" : get_posts_by_author_sql($what_to_count, TRUE, $user_id);
  $from = "FROM ".(($what_to_count == \'comment\') ? $wpdb->comments : $wpdb->posts);    
  $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) {$from} {$where}"));
  return $count;
}

Usage examples:

<?php echo atom_count(1, \'movie\'); // displays \'movie\' post type count ?>

<?php echo atom_count(1, \'comment\'); // displays comment count ?>

SO网友:chuck reynolds

在文本/HTML小部件中启用oEmbed

add_filter( \'widget_text\', array( $wp_embed, \'run_shortcode\' ), 8 );
add_filter( \'widget_text\', array( $wp_embed, \'autoembed\'), 8 );
我用它来制作youtube视频小部件和flickr之类的东西。

SO网友:EAMann

发布字数Tested on:

(最初摘自Post Word Count plug-in 通过Nick Momrick)

将已发布的单词总数添加到;“现在”;管理仪表板上的框。如果您将博客用作以下内容的出口,则很有用NaNoWriMo 或者,如果你只是想了解你的博客技能有多丰富。

function post_word_count() {
    $count = 0;
    $posts = get_posts( array(
        \'numberposts\' => -1,
        \'post_type\' => array( \'post\', \'page\' )
    ));
    foreach( $posts as $post ) {
        $count += str_word_count( strip_tags( get_post_field( \'post_content\', $post->ID )));
    }
    $num =  number_format_i18n( $count );
    // This block will add your word count to the stats portion of the Right Now box
    $text = _n( \'Word\', \'Words\', $num );
    echo "<tr><td class=\'first b\'>{$num}</td><td class=\'t\'>{$text}</td></tr>";
    // This line will add your word count to the bottom of the Right Now box.
    echo \'<p>This blog contains a total of <strong>\' . $num . \'</strong> published words!</p>\';
}

// add to Content Stats table
add_action( \'right_now_content_table_end\', \'post_word_count\');
// add to bottom of Activity Box
add_action(\'activity_box_end\', \'post_word_count\');
荣誉Rarst 对于无查询清理的代码

SO网友:NetConstructor.com

有条件地加载脚本这里有一种仅在存在特定短代码或小部件时加载脚本的方法。资料来源:Loading scripts only if a particular shortcode or widget is present

function has_my_shortcode($posts) {
    if ( empty($posts) )
        return $posts;
    $found = false;
    foreach ($posts as $post) {
        if ( stripos($post->post_content, \'[my_shortcode\') )
            $found = true;
            break;
        }
    if ($found){
        $urljs = get_bloginfo( \'template_directory\' ).IMP_JS;
    wp_register_script(\'my_script\', $urljs.\'myscript.js\' );
    wp_print_scripts(\'my_script\');
}
    return $posts;
}
add_action(\'the_posts\', \'has_my_shortcode\');

And here is how to load scripts only if a certain widget is present

要在仅加载小部件的页面中加载脚本,必须在小部件类中添加is\\u active\\u widget()代码。E、 例如,请参阅默认的最近评论小部件(wp includes/default-widgets.php,第602行):

class WP_Widget_Recent_Comments extends WP_Widget {
    function WP_Widget_Recent_Comments() {
        $widget_ops = array(\'classname\' => \'widget_recent_comments\', \'description\' => __( \'The most recent comments\' ) );
        $this->WP_Widget(\'recent-comments\', __(\'Recent Comments\'), $widget_ops);
        $this->alt_option_name = \'widget_recent_comments\';
        if ( is_active_widget(false, false, $this->id_base) )
        add_action( \'wp_head\', array(&$this, \'recent_comments_style\') );
        add_action( \'comment_post\', array(&$this, \'flush_widget_cache\') );
        add_action( \'transition_comment_status\', array(&$this, \'flush_widget_cache\') );
    }

SO网友:PNMG

Remove Private and Protected Prefix此函数删除;Privite:“私人”;标记为私有的帖子和页面的前缀。仅对登录用户或组可见的内容有用。

function the_title_trim($title) {
$title = attribute_escape($title);
$findthese = array(
    \'#Protected:#\',
    \'#Private:#\'
);
$replacewith = array(
    \'\', // What to replace "Protected:" with
    \'\' // What to replace "Private:" with
);
$title = preg_replace($findthese, $replacewith, $title);
return $title;
}
add_filter(\'the_title\', \'the_title_trim\');
EDIT: 更新内容包括删除受保护的:以及。

SO网友:Martin-Al

Custom excerpt length

function excerpt($num) {
    $limit = $num+1;
    $excerpt = explode(\' \', get_the_excerpt(), $limit);
    array_pop($excerpt);
    $excerpt = implode(" ",$excerpt)."... (<a href=\'" .get_permalink($post->ID) ." \'>Read more</a>)";
    echo $excerpt;
}
通过在主题中书写来限制显示的摘录的长度:摘录(“20”);

例子:<?php excerpt(\'22\'); ?>这将限制摘录为22个字符。

摘录将被打断... (Read More)

SO网友:Scott

将父页slug添加到body\\u类

/***************************************************************
* Function body_class_section
* Add the top level page to the body class for coloured sections
***************************************************************/

add_filter(\'body_class\',\'body_class_section\');

function body_class_section($classes) {
    global $wpdb, $post;
    if (is_page()) {
        if ($post->post_parent) {
            $parent  = end(get_post_ancestors($current_page_id));
        } else {
            $parent = $post->ID;
        }
        $post_data = get_post($parent, ARRAY_A);
        $classes[] = \'section-\' . $post_data[\'post_name\'];
    }
    return $classes;
}
此筛选器基于当前页面的最高级别父级添加唯一的正文类。我将其用于网站的每个部分都有特定颜色或布局的网站。它最适合基于页面的网站。CSS示例:

.section-about { background: red; }
.section-portfolio { background: blue; }
您的主题还必须使用body_class function.

修复嵌入的flash对象

/***************************************************************
* Function my_oembed_wmode
* Fix oEmbed window mode for flash objects
***************************************************************/

add_filter(\'embed_oembed_html\', \'my_oembed_wmode\', 1);

function my_oembed_wmode( $embed ) {
    if ( strpos( $embed, \'<param\' ) !== false ) {
        $embed = str_replace( \'<embed\', \'<embed wmode="transparent" \', $embed );
        $embed = preg_replace( \'/param>/\', \'param><param name="wmode" value="transparent" />\', $embed, 1);
    }
    return $embed;
}
我曾经遇到过这样的问题:嵌入的Flash对象与下拉导航菜单发生冲突。此过滤器通过向嵌入添加透明窗口模式来解决该问题。

从管理页面列表中删除“注释”列

/***************************************************************
* Function custom_pages_columns
* Remove "comments" from pages overview (rarely use comments on pages)
***************************************************************/

add_filter(\'manage_pages_columns\', \'custom_pages_columns\');

function custom_pages_columns($defaults) {
    unset($defaults[\'comments\']);
    return $defaults;
}
我几乎从不在页面上发表评论,这有助于保持WordPress仪表板的整洁。

SO网友:Chris_O

启用数字分页Tested on:

/* Numeric Pagination ********************************************/

function numeric_pagination ($pageCount = 9, $query = null) {

 if ($query == null) {
  global $wp_query;
  $query = $wp_query;
 }

 if ($query->max_num_pages <= 1) {
  return;
 }

 $pageStart = 1;
 $paged = $query->query_vars[\'paged\'];

 // set current page if on the first page
 if ($paged == null) {
  $paged = 1;
 }

 // work out if page start is halfway through the current visible pages and if so move it accordingly
 if ($paged > floor($pageCount / 2)) {
  $pageStart = $paged - floor($pageCount / 2);
 }

 if ($pageStart < 1) {
  $pageStart = 1;
 }

 // make sure page start is
 if ($pageStart + $pageCount > $query->max_num_pages) {
  $pageCount = $query->max_num_pages - $pageStart;
 }

?>
 <div id="archive_pagination">
<?php
 if ($paged != 1) {
?>
 <a href="<?php echo get_pagenum_link(1); ?>" class="numbered page-number-first"><span>&lsaquo; <?php _e(\'<< First\', \'global\'); ?></span></a>
<?php
 }
 // first page is not visible...
 if ($pageStart > 1) {
  //echo \'previous\';
 }
 for ($p = $pageStart; $p <= $pageStart + $pageCount; $p ++) {
  if ($p == $paged) {
?>
  <span class="numbered page-number-<?php echo $p; ?> current-numeric-page"><?php echo $p; ?></span>
<?php } else { ?>
  <a href="<?php echo get_pagenum_link($p); ?>" class="numbered page-number-<?php echo $p; ?>"><span><?php echo $p; ?></span></a>

<?php
  }
 }
 // last page is not visible
 if ($pageStart + $pageCount < $query->max_num_pages) {
  //echo "last";
 }
 if ($paged != $query->max_num_pages) {
?>
  <a href="<?php echo get_pagenum_link($query->max_num_pages); ?>" class="numbered page-number-last"><span><?php _e(\'>> Last\', \'global\'); ?> &rsaquo;</span></a>
<?php } ?>

 </div>

SO网友:bueltge

仅为登录用户显示特定内容Tested on:

function content_only4logged_in($content) {

    // ALL LOGGED IN USERS
    if ( is_user_logged_in() &&
            !is_null($content) &&
            !is_feed()
         ) {
        return $content;
    } else {
        $content  = wp_html_excerpt( $content, 80 );
        $content .= \' …\';
        $content .= __( \'Sorry, more of this content is only available for logged users.\', FB_TEXTDOMAIN );
        return $content;
    }
}
add_action( \'the_content\', \'content_only4logged_in\' );
更多的可能性和信息http://wpengineer.com/2046/control-the-wordpress-content-via-userrights-or-time/

SO网友:Dan Gayle

通过删除WWW缩短您的短链接Tested on:

如果您包括以下内容,请缩短您的短链接www. 在您的域中。通过scratch99.com:

add_filter(\'get_shortlink\',\'sjc_alter_shortlink\');
function sjc_alter_shortlink($shortlink) {
    $shortlink = preg_replace(\'/^(https?:\\/\\/)?(www\\.)/\',\'$1\',$shortlink);
    return $shortlink;
}

SO网友:t31os

检查帖子是否包含嵌入内容

检查帖子是否有嵌入内容,是否使用当前帖子的ID在循环中工作,或者可以通过传递ID来确定要检查嵌入内容的帖子。

function has_embed( $post_id = false ) {
    if( !$post_id ) $post_id = get_the_ID();
    else $post_id = absint( $post_id );
    if( !$post_id ) return false;

    $post_meta = get_post_custom_keys( $post_id );
    $post_meta = array_map( \'trim\' , $post_meta );

    foreach( $post_meta as $meta ) {
        if( \'_oembed\' != substr( $meta , 0 , 7 ) )
            continue;
        return true;
    }
    return false;
}
使用该函数的方式与检查帖子是否有标记的方式相同。。

if( has_embed() ) {
   // do whatever
}
如果找到嵌入,则函数返回true,如果失败,则返回false。

SO网友:NetConstructor.com

在主页上显示来自不同自定义帖子类型的帖子,方法是将此帖子底部的以下代码拖放到您的函数中。php文件,您可以让wordpress自动显示您创建的不同自定义帖子类型的帖子。目前默认情况下,wordpress仅显示属于默认;“发布”;岗位类型。

在下面提供的示例中,您需要更改调用以下内容的部分:

$query->set( \'post_type\', array(\'post\', \'page\', \'services\', \'attachment\'));
使用您自己的自定义帖子类型,您希望将其包含在主页帖子列表结果中。在这种情况下,我们要求wordpress将属于默认设置的所有帖子返回给我们;“发布”;和;第“”页;post\\u type然后要求wordpress也包括我们为“创建的自定义帖子类型”;“服务”;最后是默认的wordpress帖子类型;附件“;这只是意味着,任何时候,只要有东西添加到媒体库中,它就会自动显示在主页上,作为一个单独的条目。

// CUSTOM HOMEPAGE POST LIST INCLUDING DIFFERENT POST_TYPES
// make sure to edit the post types you wanted included in the list below
add_filter( \'pre_get_posts\', \'my_homepage_post_list\' );
function my_homepage_post_list ( $query ) {
    if ( is_home() && false == $query->query_vars[\'suppress_filters\'] )
        $query->set( \'post_type\', array(\'post\', \'page\', \'services\', \'attachment\'));
    return $query;
}
您还可以在不同的位置使用此自定义查询,例如通过以下内容在自定义提要中使用

if (( is_home() && false == $query->query_vars[\'suppress_filters\'] ) || is_feed())

SO网友:Nicole

预填充帖子类型

这里有一个用于此集合的帖子类型。

////////////////////////////////////////////////////////////////////////////////////
// This auto populates post types and posts.
///////////////////////////////////////////////////////////////////////////////////

add_filter( \'default_content\', \'my_editor_content\' );

function my_editor_content( $content ) {

    global $post_type;

    switch( $post_type ) {
        case \'your_post_type_here\': //auto populate
            $content = \'The content you want to pre-populate the post type with.\';
break;
     }

    return $content;
}
当你需要一次又一次地发布相同的信息,但略有不同时,这会很有用。

SO网友:EAMann

自动包含谷歌分析代码Tested on: Wordpress 3.1 RC3

自WordPress 2.3.0以来,我一直在我的所有网站上使用此脚本。。。它只是将标准的谷歌跟踪脚本添加到页脚。

// Add Google Analytics Tracking Code
function add_google_analytics() {
?>
<script type="text/javascript">
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
    try {
        var pageTracker = _gat._getTracker("UA-XXXXXXX-X");
        pageTracker._trackPageview();
    } catch(err) {}</script>
<?php
}

add_action(\'wp_footer\', \'add_google_analytics\');
只需确保更换UA-XXXXXXX-X 使用您自己的Google跟踪代码。。。

SO网友:bueltge

列出所有常数以供参考和调试Tested on:

仅当您是登录用户时才显示信息

if ( is_user_logged_in() ) {
    print(\'<pre>\');
    print_r( @get_defined_constants() );
    print(\'</pre>\');
}
以下是带有可选筛选器的版本,该筛选器将部分匹配常量名称和值:

function constants($filter = false) {

        $constants = get_defined_constants();

        if( $filter ) {

            $temp = array();

            foreach ( $constants as $key => $constant )
                if( false !== stripos( $key, $filter ) || false !== stripos( $constant, $filter ) )
                    $temp[$key] = $constant;

            $constants = $temp;
        }

        ksort( $constants );
        var_dump( $constants );
    }

SO网友:Horttcore

在本地主机上添加自动更新/插件安装程序

define (\'FS_METHOD\', \'direct\');
把这个放在你的wp配置中。php。

SO网友:Philip

Change default Author Slug

将其放入函数中,将默认的作者Slug更改为您想要的任何内容,
只需将“sellers”更改为您想要的Slug即可。

// Change URL Slug from Author to Sellers
function new_author_base() {
    global $wp_rewrite;
    $author_slug = \'sellers\';
    $wp_rewrite->author_base = $author_slug;
}
add_action(\'init\', \'new_author_base\');

SO网友:Martin-Al

在所见即所得编辑器中添加“下一页”按钮

add_filter(\'mce_buttons\',\'wysiwyg_editor\');
function wysiwyg_editor($mce_buttons) {
    $pos = array_search(\'wp_more\',$mce_buttons,true);
    if ($pos !== false) {
        $tmp_buttons = array_slice($mce_buttons, 0, $pos+1);
        $tmp_buttons[] = \'wp_page\';
        $mce_buttons = array_merge($tmp_buttons, array_slice($mce_buttons, $pos+1));
    }
    return $mce_buttons;
}

SO网友:Michal Mau

向TinyMCE编辑器添加自定义样式有时用户和客户端会对其内容在编辑器中的显示方式与在前端的显示方式感到困惑。将主样式表中的一些相关行复制到新的tinymce中。css有很大帮助:

function custom_mce_css($wp) {
    return $wp .= \',\' . get_bloginfo(\'stylesheet_directory\') . \'/css/tinymce.css\';
}
add_filter( \'mce_css\', \'custom_mce_css\' );

SO网友:Per Sandström

使用图和图标题作为标题Tested on: WordPress 3.1.3

(WP工程师学分:http://wpengineer.com/917/filter-caption-shortcode-in-wordpress/)

function mytheme_caption( $attr, $content = null ) {
    $output = apply_filters( \'img_caption_shortcode\', \'\', $attr, $content );
    if ( $output != \'\' )
        return $output;

    extract( shortcode_atts ( array(
    \'id\' => \'\',
    \'align\' => \'alignnone\',
    \'width\'=> \'\',
    \'caption\' => \'\'
    ), $attr ) );

    if ( 1 > (int) $width || empty( $caption ) )
        return $content;

    if ( $id ) $id = \'id="\' . $id . \'" \';

    return \'<figure \' . $id . \'class="wp-caption \' . $align . \'" style="width: \' . $width . \'px">\'
. do_shortcode( $content ) . \'<figcaption class="wp-caption-text">\' . $caption . \'</figcaption></figure>\';
}

add_shortcode( \'wp_caption\', \'mytheme_caption\' );
add_shortcode( \'caption\', \'mytheme_caption\' );

SO网友:Sagive

Here are some nice shortcodes for you to use:


1. Easy-to-add Twitter and Facebook share button shortcode

function shreplz() {
   return \'
    <div class="sharebox">
    <div class="twittme"><a href="https://twitter.com/share" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></div>
    <div class="shareface"><a name="fb_share"></a> <script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script></div>
    <br style="clear: left;" />
    </div>
   \';
}
add_shortcode(\'sharethis\', \'shreplz\');
// How to use: [sharethis]
<小时>

2. Easy remote site snapshot using WordPress API shortcode

function wpr_snap($atts, $content = null) {
        extract(shortcode_atts(array(
            "snap" => \'http://s.wordpress.com/mshots/v1/\',
            "url" => \'http://www.sagive.co.il\',
            "alt" => \'My image\',
            "w" => \'400\', // width
            "h" => \'300\' // height
        ), $atts));

    $img = \'<img src="\' . $snap . \'\' . urlencode($url) . \'?w=\' . $w . \'&h=\' . $h . \'" alt="\' . $alt . \'"/>\';
        return $img;
}

add_shortcode("snap", "wpr_snap");
// How to use: [snap url="http://www.example.com" alt="Cool Site!" w="300px" h="200px"]
<小时>

3. Easy to use & embed iFrame shortcode

function GenerateIframe( $atts ) {
    extract( shortcode_atts( array(
        \'href\' => \'http://the-url\',
        \'height\' => \'550px\',
        \'width\' => \'600px\',
    ), $atts ) );

    return \'<iframe src="\'.$href.\'" width="\'.$width.\'" height="\'.$height.\'"> <p>Your Browser does not support Iframes.</p></iframe>\';
}
add_shortcode(\'iframe\', \'GenerateIframe\');
// How to use: [iframe href="http://www.exmaple.com" height="480" width="640"]
<小时>一
function GenerateIframe( $atts ) {
    extract( shortcode_atts( array(
        \'href\' => \'http://the-url\',
        \'height\' => \'550px\',
        \'width\' => \'600px\',
    ), $atts ) );

    return \'<iframe src="\'.$href.\'" width="\'.$width.\'" height="\'.$height.\'"> <p>Your Browser does not support Iframes.</p></iframe>\';
}
add_shortcode(\'iframe\', \'GenerateIframe\');
// How to use: [iframe href="http://www.exmaple.com" height="480" width="640"]
Here are some comments related snippets:

1. Close the ability to comment globally

function closeCommentsGlobaly($data) { return false; }
add_filter(\'comments_number\', \'closeCommentsGlobaly\');
add_filter(\'comments_open\', \'closeCommentsGlobaly\');
<小时>

2. Give the administrator a different CSS class for the administrator\'s comments

if (1 == $comment->user_id)
    echo \'siteadmin\'; // Pick your class here
<小时>

3. A really cool rich with a data list of comments - gr8 for custom locked page

$comments = get_comments( array(
    \'number\'    => 10, // How many comments
    \'status\'    => \'approve\' // Type of comments
) );

foreach($comments as $eachComment){

    // Collect the data and assign it
    $commentID = comment_ID;
    $commentAuthorEmail = $eachComment->comment_author_email;
    $commentPostId = $eachComment->comment_post_ID;
    $commentPostTitle = get_the_title( $commentPostId );
    $commentPostUrl = get_permalink( $commentPostId );
    $comment_sidebarnumber = get_comments_number( $commentPostId );

    global $wpdb;
    $userCommentCount = $wpdb->get_var(\'SELECT COUNT(\'.$commentID.\') FROM \' . $wpdb->comments. \' WHERE comment_author_email = "\' . $commentAuthorEmail . \'"\');

    echo \'<div style="border: 1px solid #ccc; padding: 10px;">\';
    echo \'<ul style="margin: 0px;">\';
    echo \'<li>Name: \'. $eachComment->comment_author .\'</li>\';
    echo \'<li>Commented about: <a href="\'.$commentPostUrl.\'">\'. $commentPostTitle .\'</a></li>\';
    echo \'<li>Commented On: \'. $eachComment->comment_date .\'</li>\';
    echo \'<li>Commneter Site: \'. $eachComment->comment_author_email .\'</</li>\';
    echo \'<li>Commenter Email: \'. $eachComment->comment_author_email .\'</</li>\';
    echo \'<li>This Commenter\'. $eachComment->comment_author .\' Commented \'. $userCommentCount .\' on your site</</li>\';
    echo \'</ul>\';
    echo \'<p style="padding: 10px;"><strong>\'. $eachComment->comment_author .\' wrote</strong>: \'. $eachComment->comment_content .\'</p>\';
    echo \'</div>\';
}

SO网友:Norcross

Create a conditional tag for custom taxonomies

在本例中,“student”是一个自定义的post类型,“stud\\u cat”是自定义的分类法。使用has_student(null) 对于条件

    function has_student( $student, $_post = null ) {
    if ( !empty( $student ) )
        return false;
    if ( $_post )
        $_post = get_post( $_post );
    else
        $_post =& $GLOBALS[\'post\'];
    if ( !$_post )
        return false;
    $r = is_object_in_term( $_post->ID, \'studcat\', $student );
    if ( is_wp_error( $r ) )
        return false;
    return $r;
}

SO网友:chuck reynolds

使WordPress编辑器允许iFrames

// make TinyMCE allow iframes
add_filter(\'tiny_mce_before_init\', create_function( \'$a\',
\'$a["extended_valid_elements"] = "iframe[id|class|title|style|align|frameborder|height|longdesc|marginheight|marginwidth|name|scrolling|src|width]"; return $a;\') );

SO网友:Philip Downer

Easy WordPress Security Fixes

默默无闻的安全是这里的游戏名称。这些函数做三件不同的事情。

从代码中删除版本字符串。没有必要告诉人们我们正在运行的版本

  • 从管理员登录屏幕中删除任何错误消息(密码错误、没有这样的用户等)
  • 当管理员发表评论时,会添加一个CSS类。这将删除注释中的管理员名称。

    //REMOVE VERSION STRING FROM HEADER
    remove_action(\'wp_head\', \'wp_generator\');
    
    //HIDE LOGIN ERROR MESSAGES (Wrong Password, No Such User etc.)
    add_filter(\'login_errors\',create_function(\'$a\', "return null;"));
    
    // Remove admin name in comments class
    // Source: http://www.wprecipes.com/wordpress-hack-remove-admin-name-in-comments-class
    function remove_comment_author_class( $classes ) {
        foreach( $classes as $key => $class ) {
            if(strstr($class, "comment-author-")) {
                unset( $classes[$key] );
            }
        }
        return $classes;
    }
    add_filter( \'comment_class\' , \'remove_comment_author_class\' );
    
  • SO网友:Philip Downer

    Replace Default Gravatar with Custom Image

    您只需自定义默认图像的路径。

    function custom_gravatar($avatar_defaults) {
        $logo = get_bloginfo(\'template_directory\') . \'/images/icons/gravatar_logo.jpg\'; //Change to whatever path you like.
        $avatar_defaults[$logo] = get_bloginfo(\'name\');
        return $avatar_defaults;
    }//END FUNCTION    
    add_filter( \'avatar_defaults\', \'custom_gravatar\' );
    

    SO网友:dalethedeveloper

    显示要包含的模板文件

    显示带有模板文件的内联注释,并在渲染页面时获取要包含的\\u template\\u零件文件。便于对多部分模板进行故障排除。

    add_action(\'all\',\'template_snoop\');
    function template_snoop(){
        $args = func_get_args();
        if( !is_admin() and $args[0] ){
            if( $args[0] == \'template_include\' ) {
                echo "<!-- Base Template: {$args[1]} -->\\n";
            } elseif( strpos($args[0],\'get_template_part_\') === 0 ) {
                global $last_template_snoop;
                if( $last_template_snoop )
                    echo "\\n\\n<!-- End Template Part: {$last_template_snoop} -->";
                $tpl = rtrim(join(\'-\',  array_slice($args,1)),\'-\').\'.php\';
                echo "\\n<!-- Template Part: {$tpl} -->\\n\\n";
                $last_template_snoop = $tpl;
            }
        }
    }
    

    SO网友:NetConstructor.com

    Automatically create a new page upon activating a theme

    if (isset($_GET[\'activated\']) && is_admin()){
        $new_page_title = \'This is the page title\';
        $new_page_content = \'This is the page content\';
        $new_page_template = \'\'; //ex. template-custom.php. Leave blank if you don\'t want a custom page template.
    
    //don\'t edit under this line
    $page_check = get_page_by_title($new_page_title);
    $new_page = array(
        \'post_type\' => \'page\',
        \'post_title\' => $new_page_title,
        \'post_content\' => $new_page_content,
        \'post_status\' => \'publish\',
        \'post_author\' => 1,
    );
    if(!isset($page_check->ID)){
        $new_page_id = wp_insert_post($new_page);
        if(!empty($new_page_template)){
            update_post_meta($new_page_id,\'_wp_page_template\', $new_page_template);
        }
    }
    
    SO网友:bueltge

    列出所有子类别Tested on:

    $echo = \'<ul>\' . "\\n";
    $childcats = get_categories(\'child_of=\' . $cat . \'&hide_empty=1\');
    foreach ($childcats as $childcat) {
        if (1 == $childcat->category_parent) {
            $echo .= "\\t" . \'<li><a href="\' . get_category_link($childcat->cat_ID).\'" title="\' . $childcat->category_description . \'">\';
            $echo .= $childcat->cat_name . \'</a>\';
            $echo .= \'</li>\' . "\\n";
        }
    }
    $echo .= \'</ul>\' . "\\n";
    echo $echo;
    
    还有这里,更多信息和功能http://wpengineer.com/2025/list-all-subcategories/

    SO网友:NetConstructor.com

    无需删除功能即可自动清理SEO段塞Tested on:

    通过将此代码添加到函数中。php文件wordpress将通过删除所有不必要的单词自动清理slug URL标题。我还通过其他自定义扩展了这些功能,这些自定义隐藏了slug和metabox的屏幕选项。通过在下面包含代码,您创建的任何新帖子都会自动缩短,您仍然可以通过单击帖子标题下的url并保存帖子来手动编辑slug。

    // AUTOMATICALLY SANITIZE PAGE/POST SEO SLUG FROM SHORT WORDS
       add_filter(\'name_save_pre\', \'seo_slugs\', 0);
       function seo_slugs($slug) {
        // We don\'t want to change an existing slug
     if ($slug) return $slug;
     global $wpdb;
     $seo_slug = strtolower(stripslashes($_POST[\'post_title\']));
     $seo_slug = preg_replace(\'/&.+?;/\', \'\', $seo_slug); // kill HTML entities
        // kill anything that is not a letter, digit, space or apostrophe
     $seo_slug = preg_replace ("/[^a-zA-Z0-9 \\\']/", "", $seo_slug);
        // Turn it to an array and strip common words by comparing against c.w. array
     $seo_slug_array = array_diff (split(" ", $seo_slug), seo_slugs_stop_words());
        // Turn the sanitized array into a string
     $seo_slug = join("-", $seo_slug_array);
     return $seo_slug;
       }
       function seo_slugs_stop_words () {
       return array ("a", "able", "about", "above", "abroad", "according", "accordingly", "across", "actually", "adj", "after", "afterwards", "again", "against", "ago", "ahead", "ain\'t", "all", "allow", "allows", "almost", "alone", "along", "alongside", "already", "also", "although", "always", "am", "amid", "amidst", "among", "amongst", "an", "and", "another", "any", "anybody", "anyhow", "anyone", "anything", "anyway", "anyways", "anywhere", "apart", "appear", "appreciate", "appropriate", "are", "aren\'t", "around", "as", "a\'s", "aside", "ask", "asking", "associated", "at", "available", "away", "awfully", "b", "back", "backward", "backwards", "be", "became", "because", "become", "becomes", "becoming", "been", "before", "beforehand", "begin", "behind", "being", "believe", "below", "beside", "besides", "best", "better", "between", "beyond", "both", "brief", "but", "by", "c", "came", "can", "cannot", "cant", "can\'t", "caption", "cause", "causes", "certain", "certainly", "changes", "clearly", "c\'mon", "co", "co.", "com", "come", "comes", "concerning", "consequently", "consider", "considering", "contain", "containing", "contains", "corresponding", "could", "couldn\'t", "course", "c\'s", "currently", "d", "dare", "daren\'t", "definitely", "described", "despite", "did", "didn\'t", "different", "directly", "do", "does", "doesn\'t", "doing", "done", "don\'t", "down", "downwards", "during", "e", "each", "edu", "eg", "eight", "eighty", "either", "else", "elsewhere", "end", "ending", "enough", "entirely", "especially", "et", "etc", "even", "ever", "evermore", "every", "everybody", "everyone", "everything", "everywhere", "ex", "exactly", "example", "except", "f", "fairly", "far", "farther", "few", "fewer", "fifth", "first", "five", "followed", "following", "follows", "for", "forever", "former", "formerly", "forth", "forward", "found", "four", "from", "further", "furthermore", "g", "get", "gets", "getting", "given", "gives", "go", "goes", "going", "gone", "got", "gotten", "greetings", "h", "had", "hadn\'t", "half", "happens", "hardly", "has", "hasn\'t", "have", "haven\'t", "having", "he", "he\'d", "he\'ll", "hello", "help", "hence", "her", "here", "hereafter", "hereby", "herein", "here\'s", "hereupon", "hers", "herself", "he\'s", "hi", "him", "himself", "his", "hither", "hopefully", "how", "howbeit", "however", "hundred", "i", "i\'d", "ie", "if", "ignored", "i\'ll", "i\'m", "immediate", "in", "inasmuch", "inc", "inc.", "indeed", "indicate", "indicated", "indicates", "inner", "inside", "insofar", "instead", "into", "inward", "is", "isn\'t", "it", "it\'d", "it\'ll", "its", "it\'s", "itself", "i\'ve", "j", "just", "k", "keep", "keeps", "kept", "know", "known", "knows", "l", "last", "lately", "later", "latter", "latterly", "least", "less", "lest", "let", "let\'s", "like", "liked", "likely", "likewise", "little", "look", "looking", "looks", "low", "lower", "ltd", "m", "made", "mainly", "make", "makes", "many", "may", "maybe", "mayn\'t", "me", "mean", "meantime", "meanwhile", "merely", "might", "mightn\'t", "mine", "minus", "miss", "more", "moreover", "most", "mostly", "mr", "mrs", "much", "must", "mustn\'t", "my", "myself", "n", "name", "namely", "nd", "near", "nearly", "necessary", "need", "needn\'t", "needs", "neither", "never", "neverf", "neverless", "nevertheless", "new", "next", "nine", "ninety", "no", "nobody", "non", "none", "nonetheless", "noone", "no-one", "nor", "normally", "not", "nothing", "notwithstanding", "novel", "now", "nowhere", "o", "obviously", "of", "off", "often", "oh", "ok", "okay", "old", "on", "once", "one", "ones", "one\'s", "only", "onto", "opposite", "or", "other", "others", "otherwise", "ought", "oughtn\'t", "our", "ours", "ourselves", "out", "outside", "over", "overall", "own", "p", "particular", "particularly", "past", "per", "perhaps", "placed", "please", "plus", "possible", "presumably", "probably", "provided", "provides", "q", "que", "quite", "qv", "r", "rather", "rd", "re", "really", "reasonably", "recent", "recently", "regarding", "regardless", "regards", "relatively", "respectively", "right", "round", "s", "said", "same", "saw", "say", "saying", "says", "second", "secondly", "see", "seeing", "seem", "seemed", "seeming", "seems", "seen", "self", "selves", "sensible", "sent", "serious", "seriously", "seven", "several", "shall", "shan\'t", "she", "she\'d", "she\'ll", "she\'s", "should", "shouldn\'t", "since", "six", "so", "some", "somebody", "someday", "somehow", "someone", "something", "sometime", "sometimes", "somewhat", "somewhere", "soon", "sorry", "specified", "specify", "specifying", "still", "sub", "such", "sup", "sure", "t", "take", "taken", "taking", "tell", "tends", "th", "than", "thank", "thanks", "thanx", "that", "that\'ll", "thats", "that\'s", "that\'ve", "the", "their", "theirs", "them", "themselves", "then", "thence", "there", "thereafter", "thereby", "there\'d", "therefore", "therein", "there\'ll", "there\'re", "theres", "there\'s", "thereupon", "there\'ve", "these", "they", "they\'d", "they\'ll", "they\'re", "they\'ve", "thing", "things", "think", "third", "thirty", "this", "thorough", "thoroughly", "those", "though", "three", "through", "throughout", "thru", "thus", "till", "to", "together", "too", "took", "toward", "towards", "tried", "tries", "truly", "try", "trying", "t\'s", "twice", "two", "u", "un", "under", "underneath", "undoing", "unfortunately", "unless", "unlike", "unlikely", "until", "unto", "up", "upon", "upwards", "us", "use", "used", "useful", "uses", "using", "usually", "v", "value", "various", "versus", "very", "via", "viz", "vs", "w", "want", "wants", "was", "wasn\'t", "way", "we", "we\'d", "welcome", "well", "we\'ll", "went", "were", "we\'re", "weren\'t", "we\'ve", "what", "whatever", "what\'ll", "what\'s", "what\'ve", "when", "whence", "whenever", "where", "whereafter", "whereas", "whereby", "wherein", "where\'s", "whereupon", "wherever", "whether", "which", "whichever", "while", "whilst", "whither", "who", "who\'d", "whoever", "whole", "who\'ll", "whom", "whomever", "who\'s", "whose", "why", "will", "willing", "wish", "with", "within", "without", "wonder", "won\'t", "would", "wouldn\'t", "x", "y", "yes", "yet", "you", "you\'d", "you\'ll", "your", "you\'re", "yours", "yourself", "yourselves", "you\'ve", "z", "zero");
       }
    
    将下面的附加代码添加到函数时。php文件它将删除/隐藏screen options下拉列表中的slug选项以及metabox。

    // HIDE THE SLUG METABOX AND SLUG SCREEN OPTIONS
       function hide_slug_options() {
     global $post;
     global $pagenow;
     $hide_slugs = "<style type=\\"text/css\\">#slugdiv, #edit-slug-box, [for=\\"slugdiv-hide\\"] { display: none; }</style>\\n";
     if (is_admin() && $pagenow==\'post-new.php\' OR $pagenow==\'post.php\') print($hide_slugs);
       }
       add_action( \'admin_head\', \'hide_slug_options\'  );
    

    SO网友:tomcat23

    排除特定类别的子类别

       /* this code excludes all of the children of (category id = 20) posts
           on the HOME page, but allows parent (category id = 20) to be shown. */
    
        function exclude_category_children($query) {
            $child_cats = (array) get_term_children(\'20\', \'category\');
            if ( $query->is_home ) {
            $query->set(\'category__not_in\', $child_cats);
            return $query;
            }
        }
        add_filter(\'pre_get_posts\', \'exclude_category_children\');
    

    SO网友:PNMG

    检查层次结构子体的条件函数,用于检查当前页面是否是给定ID的子体。用于确定页面在层次结构树中是孙子、曾孙还是父亲。

    function is_tree($pid) {      // $pid = The ID of the page we\'re looking for pages underneath
        global $post;         // load details about this page
    
        $anc = get_post_ancestors( $post->ID );
        foreach($anc as $ancestor) {
            if(is_page() && $ancestor == $pid) {
                return true;
            }
        }
        if(is_page()&&(is_page($pid))) 
                   return true;   // we\'re at the page or at a sub page
        else 
                   return false;  // we\'re elsewhere
    };
    

    SO网友:Daniel Sachs

    Remove Admin Backend Menus for all users, except User #1 (usually the first Admin)

    /*-----------------------------------------------------------------------------------*/
    /*  Restrict access
    /*-----------------------------------------------------------------------------------*/
    function remove_menus () {
    global $menu;
    $user = wp_get_current_user();
        if ($user->ID!=1) { // Is not administrator,
    
            $restricted = array(__(\'Dashboard\'), __(\'Posts\'), __(\'Media\'), __(\'Links\'), __(\'Pages\'), __(\'Appearance\'), __(\'Tools\'), __(\'Users\'), __(\'Settings\'), __(\'Comments\'), __(\'Plugins\'));
            end ($menu);
            while (prev($menu)){
                $value = explode(\' \',$menu[key($menu)][0]);
                if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
            }
        }
    }
    add_action(\'admin_menu\', \'remove_menus\');
    
    SO网友:PrivateUser

    wordpress 3.2中的禁用浏览器升级警告

    enter image description here

    //Disable browser upgrade warning in wordpress 3.2
    function disable_browser_upgrade_warning() {
        remove_meta_box( \'dashboard_browser_nag\', \'dashboard\', \'normal\' );
    }
    add_action( \'wp_dashboard_setup\', \'disable_browser_upgrade_warning\' );
    

    SO网友:byronyasgur

    is\\u tree()条件函数

    /* Adapted from csstricks with addition of
    ancestors .... use = if(is_tree($id)) { // do stuff } ... Returns true if the
    page is  = $id OR any of it\'s children OR descendants */
    
    function is_tree($pid) {      // $pid = The ID of the page we\'re looking for pages underneath
      global $post;         // load details about this page
      $ancestors = get_post_ancestors($post);
      if(is_page()&&($post->post_parent==$pid||is_page($pid)||(in_array($pid,$ancestors))))
        return true;   // we\'re at the page or at a sub page
      else
        return false;  // we\'re elsewhere 
      };
    

    SO网友:NetConstructor.com

    Display the users that have submitted the most comments without a plugin

    function top_comment_authors($amount = 5) {
    global $wpdb;
    $results = $wpdb->get_results(\'
        SELECT
        COUNT(comment_author_email) AS comments_count, comment_author_email, comment_author, comment_author_url
        FROM \'.$wpdb->comments.\'
        WHERE comment_author_email != "" AND comment_type = "" AND comment_approved = 1
        GROUP BY comment_author_email
        ORDER BY comments_count DESC, comment_author ASC
        LIMIT \'.$amount
    );
    $output = "<ul>";
    foreach($results as $result) {
        $output .= "<li>".$result->comment_author."</li>";
    }
    $output .= "</ul>";
    echo $output;
    }
    
    您可以调用的其他选项:$result->comment\\u author\\u email$result->comments\\u count$result->comment\\u author\\u url

    SO网友:gabrielk

    尽可能获取用户的真实IP地址Tested on:

    如果您使用的是代理或负载平衡器,请将其添加到您的wp配置中。php文件或函数。php

    // Gets the user\'s real IP address
    
    $_SERVER[\'REMOTE_ADDR\'] = getRealIpAddress();
    function getRealIpAddress( $validate = true ) {
        if ( isset($_SERVER[\'HTTP_X_FORWARDED_FOR\']) && !empty($_SERVER[\'HTTP_X_FORWARDED_FOR\']) ) {
            $ips = explode(\',\', $_SERVER[\'HTTP_X_FORWARDED_FOR\']);
            $ip = trim($ips[count($ips) - 1]);
        } elseif ( isset($_SERVER[\'HTTP_X_REAL_IP\']) && !empty($_SERVER[\'HTTP_X_REAL_IP\']) ) {
            $ip = $_SERVER[\'HTTP_X_REAL_IP\'];
        } elseif ( isset($_SERVER[\'HTTP_CLIENT_IP\']) && !empty($_SERVER[\'HTTP_CLIENT_IP\']) ) {
            $ip = $_SERVER[\'HTTP_CLIENT_IP\'];
        } else {
            $ip = $_SERVER[\'REMOTE_ADDR\'];
        }
        
        if ( $validate && function_exists(\'filter_var\') &&  filter_var($ip, FILTER_VALIDATE_IP, array(\'flags\' => FILTER_FLAG_IPV4, FILTER_FLAG_NO_PRIV_RANGE, FILTER_FLAG_NO_RES_RANGE)) )
            return $ip;
        elseif ( $validate )
            return long2ip(ip2long($ip));
    
        return $ip;
    }
    

    SO网友:NetConstructor.com

    自动添加来自目录位置的标题图像,在wordpress附带的默认标题图像中,您会注意到一个额外的主题菜单,该菜单被激活,允许您选择要使用的标题图像。在默认主题代码中,这些图像被硬编码到函数中。php文件。下面的代码允许wordpress根据您可以直接在服务器(或主题文件夹)上创建的特定标题图像自动拾取新图像。

    它将自动包括任何。jpg或。jpeg文件。每个图像都必须有一个关联的缩略图文件,但这只能是原始图像的一个副本,具有不同的名称,文件名必须以“结尾”-缩略图;。关联名称用作标题外观设置中的描述,下划线将自动替换为空格。(例如,My\\u Header\\u Image\\u A.jpg,My\\u Header\\u Image\\u A=缩略图。jpg将自动显示一个描述“My Header Image A”)

    if ($handle = opendir( TEMPLATEPATH . \'/images/headers/\') ) {
        $headers = array();
        while (false !== ($file = readdir($handle))) {
            $pos = strrpos( $file, \'.\' );
            if( $pos !== false && $pos > 0 ) {
                $file_name = substr( $file, 0, $pos );
                if( strpos( $file_name, "-thumbnail" ) === false ) {
                    $file_ext = substr( $file, $pos+1 );
                    $file_ext_low = strtolower( $file_ext );
                    if( $file_ext_low == "jpg" || $file_ext_low == "jpeg" ) {
                        $headers[$file_name] = array (
                        \'url\' => \'%s/images/headers/\' . $file,
                        \'thumbnail_url\' => \'%s/images/headers/\' . $file_name ."-thumbnail." . $file_ext,
                        \'description\' => __( str_replace( "_", " ", $file_name ), \'twentyten\' )
                        );
                    }
                }
            }
        }
    closedir($handle);
    register_default_headers( $headers );
    }
    

    SO网友:kaiser

    如果评论状态为关闭,请从管理栏中删除“评论”链接。您可以将默认评论状态设置为“关闭”,但评论链接将保持不变。只需将以下内容放入functions.php 文件以根据条件将其清除。提供了两种不同的方法。

    /**
     * Disable \'Comments\' link if default status is _closed_
     */
    function remove_comments() 
    {
        $default_comment_status = get_option( \'default_comment_status\' );
    
        if ( $default_comment_status == \'closed\' ) 
        {
            remove_action( \'admin_bar_menu\', \'wp_admin_bar_comments_menu\', 50 );
    
            // optional solution using the WP_Admin_Bar class from /wp-includes/class-wp-admin-bar.php
            # global $wp_admin_bar;
            # $wp_admin_bar->remove_menu( \'comments\' );
        }
        else 
        {
            return;
        }
    }
    

    SO网友:NetConstructor.com

    Adds a custom dropdown option to WP_NAV_MENUS where the user can select a predefined css class for each menu item

    <?php function menu_item_class_select(){
        global $pagenow;
        if ($pagenow == "nav-menus.php"){
    ?>
    
    <script>
    jQuery(document).ready(function(){
        function create_dd(v){
            //create dropdown
            var dd = jQuery(\'<select class="my_class"></select>\');
            //create dropdown options
            //array with the options you want
            var classes = ["","class1","class2","class3"];
            jQuery.each(classes, function(i,val) {
                if (v == val){
                    dd.append(\'<option value="\'+val+\'" selected="selected">\'+val+\'</option>\');
                }else{
                    dd.append(\'<option value="\'+val+\'">\'+val+\'</option>\');
                }
            });
            return dd;
        }
        jQuery(".edit-menu-item-classes").each(function() {
            //add dropdown
            var t = create_dd(jQuery(this).val());
            jQuery(this).before(t);
            //hide all inputs
            jQuery(this).css("display","none");
        });
        //update input on selection
        jQuery(".my_class").bind("change", function() {
            var v = jQuery(this).val();
            var inp = jQuery(this).next();
            inp.attr("value",v);
        });
    });
    </script>
    
    <?php } }
    add_action(\'admin_footer\',\'menu_item_class_select\');
    ?>
    

    source: https://wordpress.stackexchange.com/a/33816/479

    SO网友:Zach

    Remove WordPress 3.3 Admin Bar Menu Items

    function dashboard_tweaks() {
        global $wp_admin_bar;
        $wp_admin_bar->remove_menu(\'wp-logo\');
        $wp_admin_bar->remove_menu(\'about\');
        $wp_admin_bar->remove_menu(\'wporg\');
        $wp_admin_bar->remove_menu(\'documentation\');
        $wp_admin_bar->remove_menu(\'support-forums\');
        $wp_admin_bar->remove_menu(\'feedback\');
        $wp_admin_bar->remove_menu(\'view-site\');
    }
    add_action( \'wp_before_admin_bar_render\', \'dashboard_tweaks\' );
    

    Reference: http://pastebin.com/Wrk0JPxw

    SO网友:t31os

    从公共页面排除默认类别

    从网站正面排除默认类别
    代码不包括管理区域,否则您将无法管理使用默认类别分配的帖子。

    add_filter( \'list_terms_exclusions\', \'exclude_default_cat\' );
    
    function exclude_default_cat( $exclusions ) {
        if( !is_admin() )
            $exclusions .=  "AND t.term_id != " . get_option( \'default_category\' ) . " ";
        return $exclusions;
    }
    

    SO网友:Ünsal Korkmaz

    显示登录用户的信息

    if ( is_user_logged_in() ) {
    
    }
    
    未在函数中工作。php文件。您可以使用以下代码:

    if ( !function_exists(\'is_user_logged_in\') ) :
    
     function is_user_logged_in() {
    $user = wp_get_current_user();
    
    if ( $user->id == 0 ){
    // This section if user is not logged in
    } else {
    // This section if user is logged in
    }
    }
    endif;
    

    SO网友:Daniel Sachs

    Custom Logos for Login page and Admin

    /*-----------------------------------------------------------------------------------*/
    /*  Custom logos
    /*-----------------------------------------------------------------------------------*/
    function custom_admin_logo() {
        echo \'
            <style type="text/css">
                #header-logo { background-image: url(\'.get_bloginfo(\'template_directory\').\'/path/to/images/admin-logo.png) !important; }
            </style>
        \';
    }
    add_action(\'admin_head\', \'custom_admin_logo\');
    
    function custom_login_logo() {
        echo \'<style type="text/css">
            h1 a { background-image:url(\'.get_bloginfo(\'template_directory\').\'/path/to/images/login-logo.png) !important; }
        </style>\';
    }
    
    add_action(\'login_head\', \'custom_login_logo\');
    
    SO网友:Daniel Sachs

    Remove Admin (User #1) from User list

    function your_pre_user_query($user_search) {
      $user = wp_get_current_user();
      if ($user->ID!=1) {
        global $wpdb;
        $user_search->query_where = str_replace(\'WHERE 1=1\',
          "WHERE 1=1 AND {$wpdb->users}.ID<>1",$user_search->query_where);
      }
    }
    add_action(\'pre_user_query\',\'your_pre_user_query\');
    
    SO网友:Philip Downer

    Get Attributes of Given Thumbnail

    将此函数用于循环以确定缩略图图像的宽度、高度和URL。通过内嵌CSS将缩略图图像指定为背景元素非常方便。

    /**
    * GET THUMBNAIL ATTRIBUTES
    *
    * Fetches width, heigth and URI of a thumbnail.
    *
    * @author Philip Downer <[email protected]>
    * @license http://opensource.org/licenses/gpl-license.php GNU Public License
    * @version v1.0
    *
    * @param string $return Accepts \'path\', \'width\', or \'height\'.
    * @param string $size The thumbnail size corresponding to {@link add_image_size() WP core function}.
    * @return mixed Returns the requested info, or if no \'Featured Image\' assigned, returns \'false\'.
    */
    function get_thumb_attr($return,$size=\'thumbnail\') {
        global $post;
    
        if (has_post_thumbnail($post->ID)) {
          $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), \'intro\');
          if ( $return == \'path\' ) { return $thumb[0]; }
          if ( $return == \'width\' ) { return $thumb[1]; }
          if ( $return == \'height\' ) { return $thumb[2]; }
        } else {
            return false;
        }
    }//end function
    

    SO网友:dalethedeveloper

    使用侧边栏的ID在侧边栏的上下文之外输出小部件的内容。不包括HTML之前/之后的包装。你需要知道你想要的小部件的具体ID(例如“text-5”)。

    function widget_contents($id) {
        list($type,$number) = explode(\'-\',$id);
        global $wp_registered_widgets;
        $wp_registered_widgets[$id][\'callback\'][0]->display_callback(array(\'widget_id\'=>$id),$number);
    }
    
    您可以查看wp_get_sidebars_widgets() 如果您不确定所需的确切ID。

    更完整的示例摘自/wp-includes/widgets.phpdynamic_sidebar() 功能:

    function render_widget($id) {
        global $wp_registered_widgets;
        $params = array_merge(
                array( array(\'widget_id\' => $id, \'widget_name\' => $wp_registered_widgets[$id][\'name\']) ),
                (array) $wp_registered_widgets[$id][\'params\']
        );
        $classname_ = \'\';
        foreach ( (array) $wp_registered_widgets[$id][\'classname\'] as $cn ) {
                if ( is_string($cn) )
                        $classname_ .= \'_\' . $cn;
                elseif ( is_object($cn) )
                        $classname_ .= \'_\' . get_class($cn);
        }
        $classname_ = ltrim($classname_, \'_\');
        $params[0][\'before_widget\'] = sprintf($params[0][\'before_widget\'], $id, $classname_);
    
        if ( is_callable($wp_registered_widgets[$id][\'callback\']) )
                call_user_func_array($wp_registered_widgets[$id][\'callback\'], $params);
    }
    

    SO网友:dalethedeveloper

    交叉分类标签查询

    一种缓存查询,输出get_tags() 类似于默认为Category. 你可以用$where_slug$where_tax 获取按任何其他分类法筛选的post标记。测试了WP 3.1至WP 3.3.1的SQL。

    function tags_by_other_taxonomy($where_slug,$where_tax = \'category\',$bust_cache = false) {
        $cache_key = "{$where_slug}:{$where_tax}";
        $cache = get_transient(\'tags_by_other_taxonomy\');
        $html = \'\';
        if( true !== $bust_cache and false !== $cache and isset($cache[$cache_key]) and !empty($cache[$cache_key]) ) {
                $html = $cache[$cache_key];
        } else {
            global $wpdb;
            $cat_id = $wpdb->get_var("SELECT tt.term_taxonomy_id FROM $wpdb->terms t INNER JOIN $wpdb->term_taxonomy tt ON t.term_id = tt.term_id WHERE t.slug = \'{$where_slug}\' AND tt.taxonomy = \'{$where_tax}\' LIMIT 1");
            if( !empty($cat_id) ) {
                $cat_posts = $wpdb->get_col("SELECT tr.object_id FROM $wpdb->term_relationships tr inner join $wpdb->posts p ON p.ID = tr.object_id WHERE term_taxonomy_id = {$cat_id} AND p.post_status = \'publish\' AND p.post_type = \'post\'");
                if( count($cat_posts) ) {
                    $tags = $wpdb->get_results("SELECT DISTINCT t.name,t.slug FROM $wpdb->term_taxonomy tt
                                    INNER JOIN $wpdb->term_relationships tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
                                    INNER JOIN $wpdb->terms t ON t.term_id = tt.term_id
                                    WHERE tt.taxonomy = \'post_tag\' and tr.object_id IN (".implode(\',\',$cat_posts) .\')\');
                    $html = \'<ul class="post-tags-\'.$where_slug.\'">\';
                    if( count($tags) ) {
                        foreach($tags as $tag)
                            $html .= \'<li><a href="/tag/\'.$tag->slug.\'/" title="Posts tagged with \'.$tag->name.\'">\'.$tag->name.\'</a></li>\';
                    }
                    $html .= \'</ul>\';
                    if( !is_array($cache) )
                        $cache = array();
                    $cache[$cache_key] = $html;
                    set_transient(\'sc_cross_tax\', $cache, 86400);
                }
            }
        }
        echo $html;
    }
    
    例如,获取的所有标记Published Postsnews slug类别:

    <?php echo tags_by_other_taxonomy(\'news\'); ?>
    

    SO网友:NetConstructor.com

    通过JQUERY重新定位所见即所得编辑器Tested on:

    此代码允许您删除wordpress默认情况下添加到POST和PAGES屏幕的特定元框。

    // REPOSITION WYSIWYG EDITOR THROUGH JQUERY
       add_action(\'admin_head\',\'admin_head_hook\');
       function admin_head_hook() {
     ?><style type="text/css">
      #postdiv.postarea, #postdivrich.postarea { margin:0; }
      #post-status-info { line-height:1.4em; font-size:13px; }
      .custom-wysiwyg-editor-container { margin:2px 6px 6px 6px; }
      #ed_toolbar { display:none; }
      #postdiv #ed_toolbar, #postdivrich #ed_toolbar { display:block; }
     </style><?php
       }
    
       add_action(\'admin_footer\',\'admin_footer_hook\');
       function admin_footer_hook() {
     ?><script type="text/javascript">
      jQuery(\'#postdiv, #postdivrich\').prependTo(\'.custom-wysiwyg-editor-container\');
     </script><?php
       }
    

    SO网友:NetConstructor.com

    从所见即所得编辑器自动关闭缺失的标记Tested on:

    使用所见即所得编辑器时,此代码将自动关闭任何丢失的标记。

    // AUTOMATICALLY CLEAN UP HTML WYSIWYG EDITOR BY CLOSING MISSING TAGS
       function clean_bad_content($bPrint = false) {
     global $post;
     $szPostContent  = $post->post_content;
     $szRemoveFilter = array("~<p[^>]*>\\s?</p>~", "~<a[^>]*>\\s?</a>~", "~<font[^>]*>~", "~<\\/font>~", "~style\\=\\"[^\\"]*\\"~", "~<span[^>]*>\\s?</span>~");
     $szPostContent  = preg_replace($szRemoveFilter, \'\', $szPostContent);
     $szPostContent  = apply_filters(\'the_content\', $szPostContent);
     if ($bPrint == false) return $szPostContent; 
     else echo $szPostContent;
       }
    

    SO网友:haha

    删除role="search" 的属性get_search_form()

    function remove_role_search($role)
    {
        $result = array();
        preg_match_all(\'|role="[^"]*"|U\', $role, $result);
        foreach ($result[0] as $role_tag) {
            $role = str_replace($role_tag, \'\', $role);
        }
        return $role;
    }
    add_filter(\'get_search_form\', \'remove_role_search\');
    

    SO网友:Rev. Voodoo

    Add a Login Link to wp_nav_menu

    //ADD LOGIN LINK TO MENU
    add_filter(\'wp_nav_menu_items\', \'add_login_logout_link\', 10, 2);
    
    function add_login_logout_link($items, $args) { 
    
            $loginoutlink = wp_loginout(\'index.php\', false); 
    
            $items .= \'<li>\'. $loginoutlink .\'</li>\'; 
    
        return $items; 
    }
    
    SO网友:dani

    Changing "Posts" menu name in admin to whatever you wish (e.g. "Articles")

    // hook the translation filters
    add_filter(\'gettext\',\'change_post_to_article\');
    add_filter(\'ngettext\',\'change_post_to_article\');
    
    function change_post_to_article( $translated ) {
    $translated = str_ireplace(\'Post\',\'Article\',$translated );// ireplace is PHP5 only
    return $translated;
    }
    

    Credits to smashingmagazine.com

    SO网友:Philip Downer

    Remove Links Menu Item

    我的许多WordPress安装不需要用户访问“链接”菜单项。此函数将其从视图中删除。

    add_action( \'admin_menu\', \'custom_admin_menu\' );
    function custom_admin_menu() 
    {
        global $menu;
        // var_dump($menu); // use this to identify the key for the menu item you want to remove
        unset( $menu[15] ); //key 15 is links
        if ( !current_user_can(\'manage_options\') ) { unset( $menu[75] ); } //key 75 is tools ... but only for non super admins
    }
    

    SO网友:Philip Downer

    Disable Upgrade Now Message for Non-Administrators

    实际上,我非常喜欢不使用此代码。相反,我更喜欢允许客户更新自己的WordPress安装。这有助于保持网站最新,并迫使我编写更好的代码。

    if ( !current_user_can( \'manage_options\' ) ) {
      add_action( \'init\', create_function( \'$a\', "remove_action( \'init\', \'wp_version_check\' );" ), 2 );
      add_filter( \'pre_option_update_core\', create_function( \'$a\', "return null;" ) );
    }
    

    SO网友:NetConstructor.com

    Add a custom class to the next and previous links

    add_filter(\'next_posts_link_attributes\', \'posts_link_attributes\');
    add_filter(\'previous_posts_link_attributes\', \'posts_link_attributes\');
    function posts_link_attributes(){
        return \'class="styled-button"\';
        }
    
    SO网友:NetConstructor.com

    Automatically add a hidden custom field and associating value to a post when the post is published

    add_action(\'publish_page\', \'add_custom_field_automatically\');
    add_action(\'publish_post\', \'add_custom_field_automatically\');
    function add_custom_field_automatically($post_ID) {
    global $wpdb;
    if(!wp_is_post_revision($post_ID)) {
        add_post_meta($post_ID, \'field-name\', \'custom value\', true);
    }
    }
    
    SO网友:NetConstructor.com

    Add custom post types to archives page

    function namespace_add_custom_types( $query ) {
    if( is_category() || is_tag() && empty( $query->query_vars[\'suppress_filters\'] ) ) {
    $query->set( \'post_type\', array(
     \'post\', \'your-custom-post-type-here\'
                ));
          return $query;
        }
    }
    add_filter( \'pre_get_posts\', \'namespace_add_custom_types\' );
    
    SO网友:jackreichert

    使用短代码调用bloginfo

    function digwp_bloginfo_shortcode($atts) {
        
        extract(shortcode_atts(array(
                \'key\' => \'\',
                ), $atts));
        
        return get_bloginfo($key);
    }
    
    add_shortcode(\'bloginfo\', \'digwp_bloginfo_shortcode\');
    

    Usage:

    [bloginfo key=\'name\']
    

    结束

    相关推荐

    WP-ADMIN似乎正在重定向

    我的w-admin登录有一个奇怪的问题。这是从我升级到3.0以后才开始的,当我转到wp admin时,登录表单显示正常,但当我输入用户名并通过时,每次都会再次显示登录表单。使用密码恢复功能会导致电子邮件未找到错误。我知道用户名密码和电子邮件是正确的,b/c我可以访问mysql数据库,我可以看到值(至少用户名和电子邮件) 有人知道会出什么问题吗