728x90

add_query_arg()

Retrieves a modified URL query string.


Description Description

You can rebuild the URL and append query variables to the URL query by using this function. There are two ways to use this function; either a single key and value, or an associative array.

Using a single key and value:

add_query_arg( 'key', 'value', 'http://example.com' );

Using an associative array:

add_query_arg( array(
    'key1' => 'value1',
    'key2' => 'value2',
), 'http://example.com' );

Omitting the URL from either use results in the current URL being used (the value of $_SERVER['REQUEST_URI']).

Values are expected to be encoded appropriately with urlencode() or rawurlencode().

Setting any query variable’s value to boolean false removes the key (see remove_query_arg()).

Important: The return value of add_query_arg() is not escaped by default. Output should be late-escaped with esc_url() or similar to help prevent vulnerability to cross-site scripting (XSS) attacks.


Parameters Parameters

$key

(string|array) (Required) Either a query variable key, or an associative array of query variables.

$value

(string) (Optional) Either a query variable value, or a URL to act upon.

$url

(string) (Optional) A URL to act upon.


Top ↑

Return Return

(string) New URL query string (unescaped).


Top ↑

Source Source

File: wp-includes/functions.php

776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
function add_query_arg() {
    $args = func_get_args();
    if ( is_array( $args[0] ) ) {
        if ( count( $args ) < 2 || false === $args[1] )
            $uri = $_SERVER['REQUEST_URI'];
        else
            $uri = $args[1];
    } else {
        if ( count( $args ) < 3 || false === $args[2] )
            $uri = $_SERVER['REQUEST_URI'];
        else
            $uri = $args[2];
    }
 
    if ( $frag = strstr( $uri, '#' ) )
        $uri = substr( $uri, 0, -strlen( $frag ) );
    else
        $frag = '';
 
    if ( 0 === stripos( $uri, 'http://' ) ) {
        $protocol = 'http://';
        $uri = substr( $uri, 7 );
    } elseif ( 0 === stripos( $uri, 'https://' ) ) {
        $protocol = 'https://';
        $uri = substr( $uri, 8 );
    } else {
        $protocol = '';
    }
 
    if ( strpos( $uri, '?' ) !== false ) {
        list( $base, $query ) = explode( '?', $uri, 2 );
        $base .= '?';
    } elseif ( $protocol || strpos( $uri, '=' ) === false ) {
        $base = $uri . '?';
        $query = '';
    } else {
        $base = '';
        $query = $uri;
    }
 
    wp_parse_str( $query, $qs );
    $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
    if ( is_array( $args[0] ) ) {
        foreach ( $args[0] as $k => $v ) {
            $qs[ $k ] = $v;
        }
    } else {
        $qs[ $args[0] ] = $args[1];
    }
 
    foreach ( $qs as $k => $v ) {
        if ( $v === false )
            unset( $qs[$k] );
    }
 
    $ret = build_query( $qs );
    $ret = trim( $ret, '?' );
    $ret = preg_replace( '#=(&|$)#', '$1', $ret );
    $ret = $protocol . $base . $ret . $frag;
    $ret = rtrim( $ret, '?' );
    return $ret;
}

Top ↑

Changelog Changelog

Changelog
VersionDescription
1.5.0Introduced.

Top ↑

More Information More Information

Usage Usage

1
2
3
4
5
6
7
8
9
10
11
12
// Parameters as separate arguments
add_query_arg( $param1, $param2, $old_query_or_uri );
 
// Parameters as array of key => value pairs
add_query_arg(
    array(
        'key1' => 'value1',
        'key2' => 'value2',
        ...
    ),
    $old_query_or_uri
);


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note content
    Contributed by Codex — 

    Assuming we’re at the WordPress URL “http://blog.example.com/client/?s=word”… Note the use of esc_url() before outputting the link. This is necessary because this function does not escape URLs and if output without escaping, would make the page vulnerable to XSS scripting.

    1
    2
    3
    4
    5
    6
    // This would output '/client/?s=word&foo=bar'
    echo esc_url( add_query_arg( 'foo', 'bar' ) );
     
    // This would output '/client/?s=word&foo=bar&baz=tiny'
    $arr_params = array( 'foo' => 'bar', 'baz' => 'tiny' );
    echo esc_url( add_query_arg( $arr_params ) );
  2. Skip to note content
    Contributed by Codex — 

    Since get_permalink() returns a full URL, you could use that when you want to add variables to a post’s page.

    1
    2
    3
    4
    5
    /*
     * This would output whatever the URL to post ID 9 is, with 'hello=there'
     * appended with either ? or &, depending on what's needed.
     */
    echo esc_url( add_query_arg( 'hello', 'there', get_permalink( 9 ) ) );
  3. Skip to note content
    Contributed by Codex — 

    More often than not you’ll probably find yourself creating URLs using the following method within the page you’re currently on. In these cases you can use the URL you want to affect as the last parameter. The use of esc_url() is not required here, because the value is known to be safe.

    1
    2
    echo esc_url( add_query_arg( 'hello', 'world', 'http://blog.example.com/2009/04/16/' ) );

You must log in before being able to contribute a note or feedback.


728x90

Query.getScript()

원문 링크  http://api.jquery.com/jQuery.getScript/

jQuery.getScript( url [, success(script, textStatus, jqXHR)] )Returns : jqXHR

개요 : HTTP GET 방식 요청을 통해 서버로부터 받은 JavaScript 파일을 로드하고 실행합니다.

  • jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
  • url 정보를 요청할 URL
  • success(data, textStatus, jqXHR) 요청이 성공하면 실행될 콜백 함수

이 함수의 가장 간단한 사용법은 아래와 같습니다.

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

스크립트가 실행되면 다른 변수에서 접근이 가능하고 jQuery 함수에서도 사용할 수 있습니다. 포함된 스크립트는 현재 페이지에 영향을 줄 수 있습니다.

Success Callback

이 콜백함수는 JavaScript 파일을 반환 받습니다. 스크립트가 이미 이 시점에서 실행되므로 이것은 일반적으로 유용하지 않습니다.

$(".result").html("<p>Lorem ipsum dolor sit amet.</p>");

스크립트는 파일이름을 참고한 후 로드하고 실행됩니다.

$.getScript("ajax/test.js", function(data, textStatus, jqxhr) {
   console.log(data); //data returned
   console.log(textStatus); //success
   console.log(jqxhr.status); //200
   console.log('Load was performed.');
});

Handling Errors

jQuery 1.5 부터 .fail() 함수를 사용할 수 있게 되었습니다.

$.getScript("ajax/test.js")
.done(function(script, textStatus) {
  console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
  $( "div.log" ).text( "Triggered ajaxError handler." );
});  

jQuery 1.5 이전 버젼에서는, .ajaxError() 콜백 이벤트에 $.getScript() 에러 처리 구문을 포함해서 사용해야 합니다.

$( "div.log" ).ajaxError(function(e, jqxhr, settings, exception) {
  if (settings.dataType=='script') {
    $(this).text( "Triggered ajaxError handler." );
  }
});

Caching Responses

기본적으로 $.getScript() 의 cache 속성값은 false 입니다. 스크립트를 요청시에 URL에 timestamped 를 포함하여 브라우져가 항상 새로운 스크립트를 요청하도록 하십시오. cache 속성의 전역값을 새로 세팅하려면 $.ajaxSetup()에서 하셔야 합니다.

$.ajaxSetup({
  cache: true
});

예 제  
캐싱된 스크립트를 가져올 수 있도록 $.cachedScript() 함수에서 정의합니다.

jQuery.cachedScript = function(url, options) {

  // allow user to set any option except for dataType, cache, and url
  options = $.extend(options || {}, {
    dataType: "script",
    cache: true,
    url: url
  });

  // Use $.ajax() since it is more flexible than $.getScript
  // Return the jqXHR object so we can chain callbacks
  return jQuery.ajax(options);
};

// Usage
$.cachedScript("ajax/test.js").done(function(script, textStatus) {
  console.log( textStatus );
});

음, 솔직히 말씀드려서 위 예제가 실행되면 어떻게 된다는 건지 정확하게 모르겠습니다. :-(

 

예 제  
공식 jQuery 컬러 애니메이션 플러그인 파일을 로드하고 특정 컬러를 반영합니다.

<!DOCTYPE html>
<html>
<head>
  <style>
.block {
   background-color: blue;
   width: 150px;
   height: 70px;
   margin: 10px;
}</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<button id="go">&raquo; Run</button>

<div class="block"></div>

<script>
$.getScript("/scripts/jquery.color.js", function() {
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: "pink" }, 1000)
      .delay(500)
      .animate( { backgroundColor: "blue" }, 1000);
  });
});
</script>

</body>
</html>

미리보기

jquery.color.js 파일을 열어보세요. 무지 복잡하게 뭐라무라 되어 있네요. 그중에 colors = jQuery.Color.names 변수에 위 예제에 있는 blue와 pink 에 대한 16진수 값이 들어 있습니다. 그 js 파일을 열어서 관련 로직을 반영시키는 것입니다.

 

음;;; 이 방식이 딱히 필요한지 모르겠습니다만.... 어디선가 쓸일이 있을지도 모르겠네요. 사용해 보신 분들 사례 좀 말씀해 주세용!!

※ 본 예제는 http://www.jquery.com 에 있는 내용임을 밝힙니다.



출처: http://findfun.tistory.com/397 [즐거움을 찾자 Find Fun!!]

출처: http://findfun.tistory.com/397 [즐거움을 찾자 Find Fun!!]

출처: http://findfun.tistory.com/397 [즐거움을 찾자 Find Fun!!]

'WEB > jQuery' 카테고리의 다른 글

특정 div 프린트 하기  (0) 2018.05.11
Returning JSON data using jQuery POST function from server  (0) 2018.05.10
Refresh Part of Page (div)  (0) 2018.04.13
jQuery Select Box Control  (0) 2018.04.13
turn.js  (0) 2018.03.08
728x90

dbDelta( string|array $queries = ''bool $execute = true )

Modifies the database based on specified SQL statements.


Description Description

Useful for creating new tables and updating existing tables to a new structure.


Parameters Parameters

$queries

(string|array) (Optional) The query to run. Can be multiple queries in an array, or a string of queries separated by semicolons.

Default value: ''

$execute

(bool) (Optional) Whether or not to execute the query right away.

Default value: true


Top ↑

Return Return

(array) Strings containing the results of the various update queries.


Top ↑

Source Source

File: wp-admin/includes/upgrade.php

2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
function dbDelta( $queries = '', $execute = true ) {
    global $wpdb;
 
    if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) )
        $queries = wp_get_db_schema( $queries );
 
    // Separate individual queries into an array
    if ( !is_array($queries) ) {
        $queries = explode( ';', $queries );
        $queries = array_filter( $queries );
    }
 
    /**
     * Filters the dbDelta SQL queries.
     *
     * @since 3.3.0
     *
     * @param array $queries An array of dbDelta SQL queries.
     */
    $queries = apply_filters( 'dbdelta_queries', $queries );
 
    $cqueries = array(); // Creation Queries
    $iqueries = array(); // Insertion Queries
    $for_update = array();
 
    // Create a tablename index for an array ($cqueries) of queries
    foreach ($queries as $qry) {
        if ( preg_match( "|CREATE TABLE ([^ ]*)|", $qry, $matches ) ) {
            $cqueries[ trim( $matches[1], '`' ) ] = $qry;
            $for_update[$matches[1]] = 'Created table '.$matches[1];
        } elseif ( preg_match( "|CREATE DATABASE ([^ ]*)|", $qry, $matches ) ) {
            array_unshift( $cqueries, $qry );
        } elseif ( preg_match( "|INSERT INTO ([^ ]*)|", $qry, $matches ) ) {
            $iqueries[] = $qry;
        } elseif ( preg_match( "|UPDATE ([^ ]*)|", $qry, $matches ) ) {
            $iqueries[] = $qry;
        } else {
            // Unrecognized query type
        }
    }
 
    /**
     * Filters the dbDelta SQL queries for creating tables and/or databases.
     *
     * Queries filterable via this hook contain "CREATE TABLE" or "CREATE DATABASE".
     *
     * @since 3.3.0
     *
     * @param array $cqueries An array of dbDelta create SQL queries.
     */
    $cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
 
    /**
     * Filters the dbDelta SQL queries for inserting or updating.
     *
     * Queries filterable via this hook contain "INSERT INTO" or "UPDATE".
     *
     * @since 3.3.0
     *
     * @param array $iqueries An array of dbDelta insert or update SQL queries.
     */
    $iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
 
    $text_fields = array( 'tinytext', 'text', 'mediumtext', 'longtext' );
    $blob_fields = array( 'tinyblob', 'blob', 'mediumblob', 'longblob' );
 
    $global_tables = $wpdb->tables( 'global' );
    foreach ( $cqueries as $table => $qry ) {
        // Upgrade global tables only for the main site. Don't upgrade at all if conditions are not optimal.
        if ( in_array( $table, $global_tables ) && ! wp_should_upgrade_global_tables() ) {
            unset( $cqueries[ $table ], $for_update[ $table ] );
            continue;
        }
 
        // Fetch the table column structure from the database
        $suppress = $wpdb->suppress_errors();
        $tablefields = $wpdb->get_results("DESCRIBE {$table};");
        $wpdb->suppress_errors( $suppress );
 
        if ( ! $tablefields )
            continue;
 
        // Clear the field and index arrays.
        $cfields = $indices = $indices_without_subparts = array();
 
        // Get all of the field names in the query from between the parentheses.
        preg_match("|\((.*)\)|ms", $qry, $match2);
        $qryline = trim($match2[1]);
 
        // Separate field lines into an array.
        $flds = explode("\n", $qryline);
 
        // For every field line specified in the query.
        foreach ( $flds as $fld ) {
            $fld = trim( $fld, " \t\n\r\0\x0B," ); // Default trim characters, plus ','.
 
            // Extract the field name.
            preg_match( '|^([^ ]*)|', $fld, $fvals );
            $fieldname = trim( $fvals[1], '`' );
            $fieldname_lowercased = strtolower( $fieldname );
 
            // Verify the found field name.
            $validfield = true;
            switch ( $fieldname_lowercased ) {
                case '':
                case 'primary':
                case 'index':
                case 'fulltext':
                case 'unique':
                case 'key':
                case 'spatial':
                    $validfield = false;
 
                    /*
                     * Normalize the index definition.
                     *
                     * This is done so the definition can be compared against the result of a
                     * `SHOW INDEX FROM $table_name` query which returns the current table
                     * index information.
                     */
 
                    // Extract type, name and columns from the definition.
                    preg_match(
                          '/^'
                        .   '(?P<index_type>'             // 1) Type of the index.
                        .       'PRIMARY\s+KEY|(?:UNIQUE|FULLTEXT|SPATIAL)\s+(?:KEY|INDEX)|KEY|INDEX'
                        .   ')'
                        .   '\s+'                         // Followed by at least one white space character.
                        .   '(?:'                         // Name of the index. Optional if type is PRIMARY KEY.
                        .       '`?'                      // Name can be escaped with a backtick.
                        .           '(?P<index_name>'     // 2) Name of the index.
                        .               '(?:[0-9a-zA-Z$_-]|[\xC2-\xDF][\x80-\xBF])+'
                        .           ')'
                        .       '`?'                      // Name can be escaped with a backtick.
                        .       '\s+'                     // Followed by at least one white space character.
                        .   ')*'
                        .   '\('                          // Opening bracket for the columns.
                        .       '(?P<index_columns>'
                        .           '.+?'                 // 3) Column names, index prefixes, and orders.
                        .       ')'
                        .   '\)'                          // Closing bracket for the columns.
                        . '$/im',
                        $fld,
                        $index_matches
                    );
 
                    // Uppercase the index type and normalize space characters.
                    $index_type = strtoupper( preg_replace( '/\s+/', ' ', trim( $index_matches['index_type'] ) ) );
 
                    // 'INDEX' is a synonym for 'KEY', standardize on 'KEY'.
                    $index_type = str_replace( 'INDEX', 'KEY', $index_type );
 
                    // Escape the index name with backticks. An index for a primary key has no name.
                    $index_name = ( 'PRIMARY KEY' === $index_type ) ? '' : '`' . strtolower( $index_matches['index_name'] ) . '`';
 
                    // Parse the columns. Multiple columns are separated by a comma.
                    $index_columns = $index_columns_without_subparts = array_map( 'trim', explode( ',', $index_matches['index_columns'] ) );
 
                    // Normalize columns.
                    foreach ( $index_columns as $id => &$index_column ) {
                        // Extract column name and number of indexed characters (sub_part).
                        preg_match(
                              '/'
                            .   '`?'                      // Name can be escaped with a backtick.
                            .       '(?P<column_name>'    // 1) Name of the column.
                            .           '(?:[0-9a-zA-Z$_-]|[\xC2-\xDF][\x80-\xBF])+'
                            .       ')'
                            .   '`?'                      // Name can be escaped with a backtick.
                            .   '(?:'                     // Optional sub part.
                            .       '\s*'                 // Optional white space character between name and opening bracket.
                            .       '\('                  // Opening bracket for the sub part.
                            .           '\s*'             // Optional white space character after opening bracket.
                            .           '(?P<sub_part>'
                            .               '\d+'         // 2) Number of indexed characters.
                            .           ')'
                            .           '\s*'             // Optional white space character before closing bracket.
                            .        '\)'                 // Closing bracket for the sub part.
                            .   ')?'
                            . '/',
                            $index_column,
                            $index_column_matches
                        );
 
                        // Escape the column name with backticks.
                        $index_column = '`' . $index_column_matches['column_name'] . '`';
 
                        // We don't need to add the subpart to $index_columns_without_subparts
                        $index_columns_without_subparts[ $id ] = $index_column;
 
                        // Append the optional sup part with the number of indexed characters.
                        if ( isset( $index_column_matches['sub_part'] ) ) {
                            $index_column .= '(' . $index_column_matches['sub_part'] . ')';
                        }
                    }
 
                    // Build the normalized index definition and add it to the list of indices.
                    $indices[] = "{$index_type} {$index_name} (" . implode( ',', $index_columns ) . ")";
                    $indices_without_subparts[] = "{$index_type} {$index_name} (" . implode( ',', $index_columns_without_subparts ) . ")";
 
                    // Destroy no longer needed variables.
                    unset( $index_column, $index_column_matches, $index_matches, $index_type, $index_name, $index_columns, $index_columns_without_subparts );
 
                    break;
            }
 
            // If it's a valid field, add it to the field array.
            if ( $validfield ) {
                $cfields[ $fieldname_lowercased ] = $fld;
            }
        }
 
        // For every field in the table.
        foreach ( $tablefields as $tablefield ) {
            $tablefield_field_lowercased = strtolower( $tablefield->Field );
            $tablefield_type_lowercased = strtolower( $tablefield->Type );
 
            // If the table field exists in the field array ...
            if ( array_key_exists( $tablefield_field_lowercased, $cfields ) ) {
 
                // Get the field type from the query.
                preg_match( '|`?' . $tablefield->Field . '`? ([^ ]*( unsigned)?)|i', $cfields[ $tablefield_field_lowercased ], $matches );
                $fieldtype = $matches[1];
                $fieldtype_lowercased = strtolower( $fieldtype );
 
                // Is actual field type different from the field type in query?
                if ($tablefield->Type != $fieldtype) {
                    $do_change = true;
                    if ( in_array( $fieldtype_lowercased, $text_fields ) && in_array( $tablefield_type_lowercased, $text_fields ) ) {
                        if ( array_search( $fieldtype_lowercased, $text_fields ) < array_search( $tablefield_type_lowercased, $text_fields ) ) {
                            $do_change = false;
                        }
                    }
 
                    if ( in_array( $fieldtype_lowercased, $blob_fields ) && in_array( $tablefield_type_lowercased, $blob_fields ) ) {
                        if ( array_search( $fieldtype_lowercased, $blob_fields ) < array_search( $tablefield_type_lowercased, $blob_fields ) ) {
                            $do_change = false;
                        }
                    }
 
                    if ( $do_change ) {
                        // Add a query to change the column type.
                        $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN `{$tablefield->Field}` " . $cfields[ $tablefield_field_lowercased ];
                        $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
                    }
                }
 
                // Get the default value from the array.
                if ( preg_match( "| DEFAULT '(.*?)'|i", $cfields[ $tablefield_field_lowercased ], $matches ) ) {
                    $default_value = $matches[1];
                    if ($tablefield->Default != $default_value) {
                        // Add a query to change the column's default value
                        $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN `{$tablefield->Field}` SET DEFAULT '{$default_value}'";
                        $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
                    }
                }
 
                // Remove the field from the array (so it's not added).
                unset( $cfields[ $tablefield_field_lowercased ] );
            } else {
                // This field exists in the table, but not in the creation queries?
            }
        }
 
        // For every remaining field specified for the table.
        foreach ($cfields as $fieldname => $fielddef) {
            // Push a query line into $cqueries that adds the field to that table.
            $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
            $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
        }
 
        // Index stuff goes here. Fetch the table index structure from the database.
        $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
 
        if ($tableindices) {
            // Clear the index array.
            $index_ary = array();
 
            // For every index in the table.
            foreach ($tableindices as $tableindex) {
 
                // Add the index to the index data array.
                $keyname = strtolower( $tableindex->Key_name );
                $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
                $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
                $index_ary[$keyname]['index_type'] = $tableindex->Index_type;
            }
 
            // For each actual index in the index array.
            foreach ($index_ary as $index_name => $index_data) {
 
                // Build a create string to compare to the query.
                $index_string = '';
                if ($index_name == 'primary') {
                    $index_string .= 'PRIMARY ';
                } elseif ( $index_data['unique'] ) {
                    $index_string .= 'UNIQUE ';
                }
                if ( 'FULLTEXT' === strtoupper( $index_data['index_type'] ) ) {
                    $index_string .= 'FULLTEXT ';
                }
                if ( 'SPATIAL' === strtoupper( $index_data['index_type'] ) ) {
                    $index_string .= 'SPATIAL ';
                }
                $index_string .= 'KEY ';
                if ( 'primary' !== $index_name  ) {
                    $index_string .= '`' . $index_name . '`';
                }
                $index_columns = '';
 
                // For each column in the index.
                foreach ($index_data['columns'] as $column_data) {
                    if ( $index_columns != '' ) {
                        $index_columns .= ',';
                    }
 
                    // Add the field to the column list string.
                    $index_columns .= '`' . $column_data['fieldname'] . '`';
                }
 
                // Add the column list to the index create string.
                $index_string .= " ($index_columns)";
 
                // Check if the index definition exists, ignoring subparts.
                if ( ! ( ( $aindex = array_search( $index_string, $indices_without_subparts ) ) === false ) ) {
                    // If the index already exists (even with different subparts), we don't need to create it.
                    unset( $indices_without_subparts[ $aindex ] );
                    unset( $indices[ $aindex ] );
                }
            }
        }
 
        // For every remaining index specified for the table.
        foreach ( (array) $indices as $index ) {
            // Push a query line into $cqueries that adds the index to that table.
            $cqueries[] = "ALTER TABLE {$table} ADD $index";
            $for_update[] = 'Added index ' . $table . ' ' . $index;
        }
 
        // Remove the original table creation query from processing.
        unset( $cqueries[ $table ], $for_update[ $table ] );
    }
 
    $allqueries = array_merge($cqueries, $iqueries);
    if ($execute) {
        foreach ($allqueries as $query) {
            $wpdb->query($query);
        }
    }
 
    return $for_update;
}

Top ↑

Changelog Changelog

Changelog
VersionDescription
1.5.0Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note content
    Contributed by Store Locator Plus — 

    You must be very careful in your SQL command structure when creating tables with indexes.

    Here is a simple example of the proper create table syntax for a table with a primary key on a field named “id” and a secondary key on a field named “first”.

    PRIMARY KEY must be followed by TWO SPACES then the open parenthesis then the field name and a closing parenthesis.

    KEY must be followed by a SINGLE SPACE then the key name then a space then open parenthesis with the field name then a closed parenthesis.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    private function index_test_001() {
         global $wpdb;
         $table_name = $wpdb->prefix . 'dbdelta_test_001';
         $wpdb_collate = $wpdb->collate;
         $sql =
             "CREATE TABLE {$table_name} (
             id mediumint(8) unsigned NOT NULL auto_increment ,
             first varchar(255) NULL,
             PRIMARY KEY  (id),
             KEY first (first)
             )
             COLLATE {$wpdb_collate}";
     
         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
         dbDelta( $sql );
     }
  2. Skip to note content
    Contributed by Earnest Boyd — 

    Be careful not to put a COMMENT on field or key; the preg_match code doesn’t handle it. The following code is wrong (thanks to Store Locator Plus’ code).

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    private function index_test_001() {
         global $wpdb;
         $table_name = $wpdb->prefix . 'dbdelta_test_001';
         $wpdb_collate = $wpdb->collate;
         $sql =
             "CREATE TABLE {$table_name} (
             id mediumint(8) unsigned NOT NULL auto_increment ,
             first varchar(255) NULL,
             PRIMARY KEY  (id),
             KEY first (first) COMMENT 'First name'
             )
             COLLATE {$wpdb_collate}";
      
         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
         dbDelta( $sql );
     }
  3. Skip to note content
    Contributed by octag — 

    (I post here a corrected version of my previous note. Several typographical mistakes have slipped into the original version.)
    As a side-note, the dbDelta function cannot be used to drop a table from the wp_ database . A function such as the one below can be used instead (don’t forget to replace my_theme with your own theme name):

    1
    2
    3
    4
    5
    6
    7
    8
    function my_theme_drop_table ( $table_name = 'the_name_without_any_prefix' ){
        global $wpdb;
     
        $table_name_prepared = $wpdb->prefix . $table_name;
        $the_removal_query = "DROP TABLE IF EXISTS {$table_name_prepared}";
     
        $wpdb->query( $the_removal_query );
    }

    See also https://developer.wordpress.org/plugins/the-basics/uninstall-methods/.


728x90
<?php
/**
* Plugin Name: WooCommerce Offline Gateway
* Plugin URI: https://www.skyverge.com/?p=3343
* Description: Clones the "Cheque" gateway to create another manual / offline payment method; can be used for testing as well.
* Author: SkyVerge
* Author URI: http://www.skyverge.com/
* Version: 1.0.2
* Text Domain: wc-gateway-offline
* Domain Path: /i18n/languages/
*
* Copyright: (c) 2015-2016 SkyVerge, Inc. (info@skyverge.com) and WooCommerce
*
* License: GNU General Public License v3.0
* License URI: http://www.gnu.org/licenses/gpl-3.0.html
*
* @package WC-Gateway-Offline
* @author SkyVerge
* @category Admin
* @copyright Copyright (c) 2015-2016, SkyVerge, Inc. and WooCommerce
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
*
* This offline gateway forks the WooCommerce core "Cheque" payment gateway to create another offline payment method.
*/
defined( 'ABSPATH' ) or exit;
// Make sure WooCommerce is active
if ( ! in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
return;
}
/**
* Add the gateway to WC Available Gateways
*
* @since 1.0.0
* @param array $gateways all available WC gateways
* @return array $gateways all WC gateways + offline gateway
*/
function wc_offline_add_to_gateways( $gateways ) {
$gateways[] = 'WC_Gateway_Offline';
return $gateways;
}
add_filter( 'woocommerce_payment_gateways', 'wc_offline_add_to_gateways' );
/**
* Adds plugin page links
*
* @since 1.0.0
* @param array $links all plugin links
* @return array $links all plugin links + our custom links (i.e., "Settings")
*/
function wc_offline_gateway_plugin_links( $links ) {
$plugin_links = array(
'<a href="' . admin_url( 'admin.php?page=wc-settings&tab=checkout&section=offline_gateway' ) . '">' . __( 'Configure', 'wc-gateway-offline' ) . '</a>'
);
return array_merge( $plugin_links, $links );
}
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'wc_offline_gateway_plugin_links' );
/**
* Offline Payment Gateway
*
* Provides an Offline Payment Gateway; mainly for testing purposes.
* We load it later to ensure WC is loaded first since we're extending it.
*
* @class WC_Gateway_Offline
* @extends WC_Payment_Gateway
* @version 1.0.0
* @package WooCommerce/Classes/Payment
* @author SkyVerge
*/
add_action( 'plugins_loaded', 'wc_offline_gateway_init', 11 );
function wc_offline_gateway_init() {
class WC_Gateway_Offline extends WC_Payment_Gateway {
/**
* Constructor for the gateway.
*/
public function __construct() {
$this->id = 'offline_gateway';
$this->icon = apply_filters('woocommerce_offline_icon', '');
$this->has_fields = false;
$this->method_title = __( 'Offline', 'wc-gateway-offline' );
$this->method_description = __( 'Allows offline payments. Very handy if you use your cheque gateway for another payment method, and can help with testing. Orders are marked as "on-hold" when received.', 'wc-gateway-offline' );
// Load the settings.
$this->init_form_fields();
$this->init_settings();
// Define user set variables
$this->title = $this->get_option( 'title' );
$this->description = $this->get_option( 'description' );
$this->instructions = $this->get_option( 'instructions', $this->description );
// Actions
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
add_action( 'woocommerce_thankyou_' . $this->id, array( $this, 'thankyou_page' ) );
// Customer Emails
add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 10, 3 );
}
/**
* Initialize Gateway Settings Form Fields
*/
public function init_form_fields() {
$this->form_fields = apply_filters( 'wc_offline_form_fields', array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'wc-gateway-offline' ),
'type' => 'checkbox',
'label' => __( 'Enable Offline Payment', 'wc-gateway-offline' ),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Title', 'wc-gateway-offline' ),
'type' => 'text',
'description' => __( 'This controls the title for the payment method the customer sees during checkout.', 'wc-gateway-offline' ),
'default' => __( 'Offline Payment', 'wc-gateway-offline' ),
'desc_tip' => true,
),
'description' => array(
'title' => __( 'Description', 'wc-gateway-offline' ),
'type' => 'textarea',
'description' => __( 'Payment method description that the customer will see on your checkout.', 'wc-gateway-offline' ),
'default' => __( 'Please remit payment to Store Name upon pickup or delivery.', 'wc-gateway-offline' ),
'desc_tip' => true,
),
'instructions' => array(
'title' => __( 'Instructions', 'wc-gateway-offline' ),
'type' => 'textarea',
'description' => __( 'Instructions that will be added to the thank you page and emails.', 'wc-gateway-offline' ),
'default' => '',
'desc_tip' => true,
),
) );
}
/**
* Output for the order received page.
*/
public function thankyou_page() {
if ( $this->instructions ) {
echo wpautop( wptexturize( $this->instructions ) );
}
}
/**
* Add content to the WC emails.
*
* @access public
* @param WC_Order $order
* @param bool $sent_to_admin
* @param bool $plain_text
*/
public function email_instructions( $order, $sent_to_admin, $plain_text = false ) {
if ( $this->instructions && ! $sent_to_admin && $this->id === $order->payment_method && $order->has_status( 'on-hold' ) ) {
echo wpautop( wptexturize( $this->instructions ) ) . PHP_EOL;
}
}
/**
* Process the payment and return the result
*
* @param int $order_id
* @return array
*/
public function process_payment( $order_id ) {
$order = wc_get_order( $order_id );
// Mark as on-hold (we're awaiting the payment)
$order->update_status( 'on-hold', __( 'Awaiting offline payment', 'wc-gateway-offline' ) );
// Reduce stock levels
$order->reduce_order_stock();
// Remove cart
WC()->cart->empty_cart();
// Return thankyou redirect
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
}
} // end \WC_Gateway_Offline class
}


+ Recent posts