태그 보관물: pluggable

pluggable

functions.php 파일을위한 최고의 코드 콜렉션 [닫기] 왼쪽에있는 위쪽 화살표를 클릭하여 질문과

질문이나 답변의 왼쪽에있는 위쪽 화살표를 클릭하여 질문과 유용한 답변에 투표하십시오.

현재이 게시물을보고있는 다른 많은 사람들과 마찬가지로, 저는 워드 프레스 기술을 배우고 향상시키기 위해 다양한 블로그, 포럼 및 토론 그룹을 읽고 있습니다. 지난 12 개월 동안 나는 functions.php대신 파일에 코드를 추가하여 플러그인 사용을 대체하는 임무를 수행했습니다 . 플러그인이 많은 상황에서 매우 유용하다는 것에 전적으로 동의하지만 플러그인을 사용하더라도 사용 사례의 90 %에서 실제로 플러그인을 사용하면 불필요한 합병증과 호환성 문제가 발생할 수 있음을 증명했습니다. 또한 많은 경우에 그러한 플러그인은 내가 원하지 않거나 필요하지 않은 메뉴 및 기타 관리 요소를 추가했습니다.

플러그인 코드를 분석하여 원하는 코드를 제거하고 하드 코딩 할 수 있다는 사실을 자주 발견했습니다 functions.php. 이것은 불필요한 요소를 포함하지 않고도 필요한 정확한 기능을 제공했습니다.

따라서이 게시물의 목적은 독자, 관리자 / 개발자, 당신과 나와 다른 사람들과 공유하고 유용하다고 생각하고 테마 function.php파일에 추가 한 코드 비트를 사용하지 않고 WordPress를 확장하거나 향상시키기 위해 추가 한 코드 비트를 공유하려는 나의 시도입니다 . 플러그인.

여기에 답변을 제출할 때 각 코드 비트에 제목을 적어주십시오. 호환되는 것으로 알려진 워드 프레스 버전과 기능에 대해 가장 잘 설명하는 설명을 포함하고 해당되는 경우 원본에 대한 링크를 포함 시키십시오 정보를 찾은 플러그인 또는 소스.

나는 당신의 모든 답변을 기대하고 있으며, 내가 찾을 때마다 새로운 발견을 계속 추가 할 것입니다.



답변

모든 사이트 설정을 표시하는 숨겨진 관리자 기능 사용

테스트 : WordPress 3.1 RC3

이 작은 코드 조각은 아주 멋진 일을합니다. “모든 설정”에 대한 링크와 함께 설정 메뉴에 추가 옵션을 추가하여 워드 프레스 사이트와 관련하여 데이터베이스 내에있는 모든 설정의 전체 목록을 표시합니다. 아래 코드는이 링크를 관리자 만 볼 수있게하고 다른 모든 사용자에게는 숨길 수 있습니다.

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


답변

로그인 로고 및 이미지 URL 링크 수정

테스트 : WordPress 3.0.1

이 코드를 사용하면 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>';
}

편집 : 사이트 로고를 사용하여 로그인 로고를 바꾸려면 다음을 사용하여 해당 정보를 동적으로 가져옵니다 ( 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;
}


답변

검색 결과에 맞춤 게시물 유형을 포함합니다.

// MAKE CUSTOM POST TYPES SEARCHABLE
function searchAll( $query ) {
 if ( $query->is_search ) { $query->set( 'post_type', array( 'site', 'plugin', 'theme', 'person' )); }
 return $query;
}
add_filter( 'the_search_query', 'searchAll' );

기본적으로 사이트 기본 RSS 피드에 사용자 정의 게시물 유형을 추가하십시오.

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

“지금 바로”관리 대시 보드 위젯에 사용자 정의 게시물 유형 포함

여기에는 “지금 바로”대시 보드 위젯에 사용자 정의 게시물 유형과 각 유형에 대한 게시물 수가 포함됩니다.

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


답변

ADMIN 사용자를 제외한 모든 사용자에 대한 업데이트 알림 제거

테스트 : WordPress 3.0.1

이 코드는 업데이트를 사용할 수있을 때 “admin”이외의 다른 사용자에게 워드 프레스를 통지하지 않도록합니다.

// REMOVE THE WORDPRESS UPDATE NOTIFICATION FOR ALL USERS EXCEPT SYSADMIN
   global $user_login;
   get_currentuserinfo();
   if ($user_login !== "admin") { // change admin to the username that gets the updates
    add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
    add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
   }

‘admin’사용자가 아닌 관리자 사용자에게만 업데이트 알림을 표시하도록 버전이 변경되었습니다.

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


답변

Google CDN에서 jQuery로드

테스트 : WordPress 3.0.1

// even more smart jquery inclusion :)
add_action( 'init', 'jquery_register' );

// register from google and for footer
function jquery_register() {

if ( !is_admin() ) {

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

보안을 위해 WordPress 버전 정보 제거

테스트 : WordPress 3.0.1

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

프런트 엔드의 주석에 스팸 추가 및 링크 삭제

테스트 : WordPress 3.0.1

스팸을 추가하고 링크를 삭제하여 프런트 엔드에서 주석을보다 쉽게 ​​관리 할 수 ​​있습니다. **

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

RSS 피드에 공개 게시 지연

테스트 : WordPress 3.0.1

마지막으로 텍스트에서 적어도 몇 가지 오류를 발견하기 때문에 RSS 피드에 10-15 분 동안 게시하는 것을 지연시키고 싶습니다. 다른 용도로는 콘텐츠를 RSS 독자에게 제공하기 전에 하루 또는 일주일 동안 사이트에 독점 콘텐츠를 제공하려는 경우가 있습니다.

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

    if (is_feed()) {
        // timestamp in WP-format
        $now = gmdate('Y-m-d H:i:s');

        // value for wait; + device
        $wait = '10'; // integer

        // http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff
        $device = 'MINUTE'; // MINUTE, HOUR, DAY, WEEK, MONTH, YEAR

        // add SQL-sytax to default $where
        $where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";
    }
    return $where;
}
add_filter('posts_where', 'publish_later_on_feed');


답변

DB 팽창을 피하기 위해 최대 사후 개정 수를 설정하십시오.

테스트 : WordPress 3.0.1

기본값은 무한하며, 마지막 5 개의 편집 만 기억하도록 설정됩니다.

/**
 * Set the post revisions unless the constant was set in wp-config.php
 */
if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', 5);

지금까지 코덱스 페이지 편집 wp-config.php 에서 설정할 수있는 CONSTANTS에 대한 훌륭한 아이디어가 많이 있습니다 .


답변

워드 프레스 프로파일 링 도구

프로파일 링 도구를 별도의 파일에 추가하고 싶습니다. 필요한 경우 functions.php에서 포함시킵니다.

<?php
if ( !defined('SAVEQUERIES') && isset($_GET['debug']) && $_GET['debug'] == 'sql' )
    define('SAVEQUERIES', true);
if ( !function_exists('dump') ) :
/**
 * dump()
 *
 * @param mixed $in
 * @return mixed $in
 **/

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

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

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


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

function dump_stops($in = null) {
    if ( $_POST )
        return $in;
    global $sem_stops;
    global $wp_object_cache;
    $stops = '';
    foreach ( $sem_stops as $where => $stop )
        $stops .= "$where: $stop\n";
    dump("\n" . trim($stops) . "\n");
    if ( defined('SAVEQUERIES') && $_GET['debug'] == 'sql' ) {
        global $wpdb;
        foreach ( $wpdb->queries as $key => $data ) {
            $query = rtrim($data[0]);
            $duration = number_format($data[1] * 1000, 1) . 'ms';
            $loc = trim($data[2]);
            $loc = preg_replace("/(require|include)(_once)?,\s*/ix", '', $loc);
            $loc = "\n" . preg_replace("/,\s*/", ",\n", $loc) . "\n";
            dump($query, $duration, $loc);
        }
    }
    if ( $_GET['debug'] == 'cache' )
        dump($wp_object_cache->cache);
    if ( $_GET['debug'] == 'cron' ) {
        $crons = get_option('cron');
        foreach ( $crons as $time => $_crons ) {
            if ( !is_array($_crons) )
                continue;
            foreach ( $_crons as $event => $_cron ) {
                foreach ( $_cron as $details ) {
                    $date = date('Y-m-d H:m:i', $time);
                    $schedule = isset($details['schedule']) ? "({$details['schedule']})" : '';
                    if ( $details['args'] )
                        dump("$date: $event $schedule", $details['args']);
                    else
                        dump("$date: $event $schedule");
                }
            }
        }
    }
    return $in;
} # dump_stops()
add_action('init', create_function('$in', '
    return add_stop($in, "Load");
    '), 10000000);
add_action('template_redirect', create_function('$in', '
    return add_stop($in, "Query");
    '), -10000000);
add_action('wp_footer', create_function('$in', '
    return add_stop($in, "Display");
    '), 10000000);
add_action('admin_footer', create_function('$in', '
    return add_stop($in, "Display");
    '), 10000000);

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

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


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

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


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

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


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

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