Tổng hợp những đoạn code hữu ích mới nhất [Code web hay]

Bạn vui lòng NHẤN [Lấy mã giảm giá] phía trên và gửi vào zalo : 0376.367.994 để được ưu đãi lớn hơn 50% chi phí làm web nhé bạn.

1/ Đoạn code kiểm tra 1 chuỗi con trong PHP

<?php
echo strpos("I love php, I love php too!","php");
?>

2/ Đoạn code hay trong JS

2.1 Đoạn code kích hoạt sự kiện khi nhấn nút Enter trong Jquery

$(".input1").on('keyup', function (e) {
    if (e.keyCode === 13) {
        // Do something
    }
});

2.2 Tạo nút back to top trong website

$(function() {
    $("#top").on('click', function() {
        var position = $("#image").offset().top;
        $("HTML, BODY").animate({
            scrollTop: position
        }, 1000);
    });
});

 

3/ Những đoạn code hay cho Wordpress

3.1. Tắt script biểu tượng cảm xúc.

// Disable the emoji's
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');

3.2. Dọn dẹp phần header gọn gàn.

// Remove auto generated feed links
function dhs_remove_feeds() {
	remove_action( 'wp_head', 'feed_links_extra', 3 );
	remove_action( 'wp_head', 'feed_links', 2 );
	remove_action( 'wp_head', 'rsd_link');
	remove_action( 'wp_head', 'wlwmanifest_link');
	remove_action( 'wp_head', 'wp_generator');
	remove_action( 'wp_head', 'start_post_rel_link');
	remove_action( 'wp_head', 'index_rel_link');
	remove_action( 'wp_head', 'adjacent_posts_rel_link');
	remove_action( 'wp_head', 'wp_shortlink_wp_head');
}
add_action( 'after_setup_theme', 'dhs_remove_feeds' );

3.3. Ẩn bớt trường điền URL cho comments.

// Remove website field in comments
add_action('comment_form_default_fields', 'remove_website_comment_field');
function remove_website_comment_field($fields)
{
    if (isset($fields['url'])) {
        unset($fields['url']);
    }
    return $fields;
}

3.4. Quy định số ký tự tối thiểu cho comments. Nếu như một bình luận mà chỉ có 1 hoặc vài từ thì chẳng có ý nghĩa gì, đoạn code dưới đây sẽ giúp bạn quy định ký tự tối thiểu cho 1 bình luận, bạn nhìn thấy con số 70 nghĩa là 70 ký tự, bạn có thể thay đổi nhiều ký tự hơn hoặc ít hơn.

// Requires a minimum length of a comment
add_filter('preprocess_comment', 'minimal_comment_length');
function minimal_comment_length($commentdata)
{
    $minimalCommentLength = 70;
    if (strlen(trim($commentdata['comment_content'])) < $minimalCommentLength) {
        wp_die('All comments must be at least ' . $minimalCommentLength . ' characters long.');
    }
    return $commentdata;
}

3.5. Không tạo link đường dẫn trong nội dung bình luận. Nếu một ai đó cố tình chèn link vào trong nội dung bình luận thì cũng vô ích, vì nó cũng sẽ hiển thị dạng text thông thường mà thôi, nó không hề có liên kết. Điều này sẽ giúp hạn chế spam link.

// Do not create link path in the comments
remove_filter('comment_text', 'make_clickable', 9);

3.6. Tự động thêm thuộc tính nofollow cho liên kết ngoài. Nếu blog của bạn có nhiều thành viên viết bài, họ có thể chèn liên kết trỏ ra ngoài. Code này sẽ giúp tự động thêm rel=”nofollow” cho mỗi liên kết được chèn vào nội dung.


// Add nofollow
function my_nofollow($content)
{
    return stripslashes(wp_rel_nofollow($content));
}
add_filter('the_content', 'my_nofollow');

3.7. Khi bạn tìm kiếm một bài viết mà trong blog của chúng ta chỉ có 1 bài duy nhất thì nó sẽ ra trực tiếp tới trang xem chi tiết luôn mà không cần thông qua trang kết quả tìm kiếm.

// Redirect to post if there is only one search result
add_action('template_redirect', 'single_search_redirect');
function single_search_redirect()
{
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1) {
            wp_redirect(get_permalink($wp_query->posts['0']->ID));
        }
    }
}

3.8. Tắt chức năng tự động lưu bài nháp.

Cách 1: Vào trong function.php thêm đoạn code dưới đây:
// Disable post autosave
add_action('wp_print_scripts', 'disable_autosave');
function disable_autosave()
{
    wp_deregister_script('autosave');
}
Cách 2: Vào wp_config.php thêm đoạn code sau đây:
define('WP_POST_REVISIONS', false);

3.9. Xóa đi phiên bản nằm phía sau các script, đường link script của chúng ta nhìn sẽ gọn hơn.

// Remove wp version strings
function remove_wp_version_strings($src)
{
    global $wp_version;
    parse_str(parse_url($src, PHP_URL_QUERY), $query);
    if (!empty($query['ver']) && $query['ver'] === $wp_version) {
        $src = remove_query_arg('ver', $src);
    }
    return $src;
}
add_filter('script_loader_src', 'remove_wp_version_strings');
add_filter('style_loader_src', 'remove_wp_version_strings');

3.10. Thêm thuộc tính tải không đồng bộ, điều này sẽ giúp website của chúng ta tải nhanh hơn, website sẽ load nội dung và css trước, sau đó mới load script. Dưới đây là hai đoạn code giúp tải không đồng bộ, nhưng cách viết khác nhau, bạn chỉ sử dụng một trong hai đoạn thôi nhé, mỗi dấu // là một đoạn.


// Asynchronous load JS
function defer_parsing_of_js ( $url ) {
    if ( FALSE === strpos( $url, '.js' ) ) return $url;
    return "$url' async defer='defer";
}
add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );

// Asynchronous load JS
function async_js($tag){
$scripts_to_async = array('jquery.js', 'jquery-migrate.min.js');
foreach($scripts_to_async as $async_script){
    if(true == strpos($tag, $async_script ) )
    return str_replace(' src', ' async="async" src', $tag);    
}
return $tag;
}
add_filter( 'script_loader_tag', 'async_js', 10);

3.11 Bật tính năng DEBUG và LOG trong wordpress

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true );
define('WP_DEBUG_DISPLAY', true);

3.12 Xóa chữ “Product” trên thanh điều hướng

/*
 * Hide "Products" in WooCommerce breadcrumb
 */
function woo_custom_filter_breadcrumbs_trail ( $trail ) {
  foreach ( $trail as $k => $v ) {
    if ( strtolower( strip_tags( $v ) ) == 'products' ) {
      unset( $trail[$k] );
      break;
    }
  }
 
  return $trail;
}
 
add_filter( 'woo_breadcrumbs_trail', 'woo_custom_filter_breadcrumbs_trail', 10 );

3.13 Tự thêm sản phẩm vào giỏ mỗi khi khách truy cập vào

/*
 * Add item to cart on visit
 */
function add_product_to_cart() {
        if ( ! is_admin() ) {
                global $woocommerce;
                $product_id = 64;
                $found = false;
                //check if product already in cart
                if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
                        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
                                $_product = $values['data'];
                                if ( $_product->id == $product_id )
                                        $found = true;
                        }
                        // if product not found, add it
                        if ( ! $found )
                                $woocommerce->cart->add_to_cart( $product_id );
                } else {
                        // if no products in cart, add it
                        $woocommerce->cart->add_to_cart( $product_id );
                }
        }
}
add_action( 'init', 'add_product_to_cart' );

3.14 Thêm ký hiệu tiền tệ theo ý mình

add_filter( 'woocommerce_currencies', 'add_my_currency' );
 
function add_my_currency( $currencies ) {
     $currencies['VNĐ'] = __( 'Vietnam Dong', 'woocommerce' );
     return $currencies;
}
 
add_filter('woocommerce_currency_symbol', 'add_my_currency_symbol', 10, 2);
 
function add_my_currency_symbol( $currency_symbol, $currency ) {
     switch( $currency ) {
          case 'VNĐ': $currency_symbol = '$'; break;
     }
     return $currency_symbol;
}

3.15 Thay chữ “Add to Cart” hoặc “Thêm vào giỏ”

/**
 * Change the add to cart text on single product pages
 */
function woo_custom_cart_button_text() {
        return __('My Button Text', 'woocommerce');
}
add_filter('single_add_to_cart_text', 'woo_custom_cart_button_text');
 
/**
 * Change the add to cart text on product archives
 */
function woo_archive_custom_cart_button_text() {
        return __( 'My Button Text', 'woocommerce' );
}
add_filter( 'add_to_cart_text', 'woo_archive_custom_cart_button_text' );

3.16 Tự chuyển tới trang thanh toán sau khi thêm vào giỏ

Hiện tại tính năng này không cần sử dụng code nữa mà bạn có thể bật trong Woocommerce -> Settings -> Products -> Display và chọn Redirect to the cart page after successful addition.

3.17 Gửi email sau khi thanh toán bằng coupon

/**
 * WooCommerce Extra Feature
 * --------------------------
 *
 * Send an email each time an order with coupon(s) is completed
 * The email contains coupon(s) used during checkout process
 *
 */
function woo_email_order_coupons( $order_id ) {
        $order = new WC_Order( $order_id );
 
        if( $order->get_used_coupons() ) {
 
          $to = 'youremail@yourcompany.com';
                $subject = 'New Order Completed';
                $headers = 'From: My Name ' . "\r\n";
 
                $message = 'A new order has been completed.\n';
                $message .= 'Order ID: '.$order_id.'\n';
                $message .= 'Coupons used:\n';
 
                foreach( $order->get_used_coupons() as $coupon) {
                        $message .= $coupon.'\n';
                }
                @wp_mail( $to, $subject, $message, $headers );
        }
}
add_action( 'woocommerce_thankyou', 'woo_email_order_coupons' );

3.18 Thay đổi số lượng sản phẩm liên quan

/**
 * WooCommerce Extra Feature
 * --------------------------
 *
 * Change number of related products on product page
 * Set your own value for 'posts_per_page'
 *
 */
function woo_related_products_limit() {
  global $product;
 
        $args = array(
                'post_type'                     => 'product',
                'no_found_rows'                 => 1,
                'posts_per_page'                => 6,
                'ignore_sticky_posts'   => 1,
                'orderby'               => $orderby,
                'post__in'              => $related,
                'post__not_in'          => array($product->id)
        );
        return $args;
}
add_filter( 'woocommerce_related_products_args', 'woo_related_products_limit' );

3.19 Không cho hiển thị sản phẩm trong category nào đó ở trang Shop

Thay chữ shoes thành slug của category sản phẩm mà bạn cần loại bỏ, có thể thêm nhiều bằng cách điền như array( 'shoes', 'computer' ).

/**
 * Remove products from shop page by category
 *
 */
function woo_custom_pre_get_posts_query( $q ) {
 
        if ( ! $q->is_main_query() ) return;
        if ( ! $q->is_post_type_archive() ) return;
 
        if ( ! is_admin() && is_shop() ) {
 
                $q->set( 'tax_query', array(array(
                        'taxonomy' => 'product_cat',
                        'field' => 'slug',
                        'terms' => array( 'shoes' ), // Don't display products in the shoes category on the shop page
                        'operator' => 'NOT IN'
                )));
 
        }
 
        remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
 
}
add_action( 'pre_get_posts', 'woo_custom_pre_get_posts_query' );

3.20 Tắt các tab như Review, Description trong sản phẩm

/**
 * Remove product tabs
 *
 */
function woo_remove_product_tab($tabs) {
 
    unset( $tabs['description'] );                      // Remove the description tab
    unset( $tabs['reviews'] );                                  // Remove the reviews tab
    unset( $tabs['additional_information'] );   // Remove the additional information tab
 
        return $tabs;
 
}
add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tab', 98);

3.21  Thay chữ “Free” thành một chữ bất kỳ

/**
 * WooCommerce Extra Feature
 * --------------------------
 *
 * Replace "Free!" by a custom string
 *
 */
function woo_my_custom_free_message() {
        return "Liên hệ để lấy giá";
}
 
add_filter('woocommerce_free_price_html', 'woo_my_custom_free_message');

3.22 Ẩn các phương thức vận chuyển khác khi phương thức miễn phí kích hoạt

// Hide ALL shipping options when free shipping is available
add_filter( 'woocommerce_available_shipping_methods', 'hide_all_shipping_when_free_is_available' , 10, 1 );
 
/**
* Hide ALL Shipping option when free shipping is available
*
* @param array $available_methods
*/
function hide_all_shipping_when_free_is_available( $available_methods ) {
 
        if( isset( $available_methods['free_shipping'] ) ) :
 
                // Get Free Shipping array into a new array
                $freeshipping = array();
                $freeshipping = $available_methods['free_shipping'];
 
                // Empty the $available_methods array
                unset( $available_methods );
 
                // Add Free Shipping back into $avaialble_methods
                $available_methods = array();
                $available_methods[] = $freeshipping;
 
        endif;
 
        return $available_methods;
}

 

4/ Đoạn code hay dành cho lập trình Android

4.1.Replace fragment kèm theo Animation

private void replaceFragment(Fragment fragment) {
    FragmentManager manager = getSupportFragmentManager();
   FragmentTransaction transaction = manager.beginTransaction();
   transaction.setCustomAnimations(R.anim.slide_in_right,R.anim.slide_out_left)
   .replace(R.id.content_main, fragment)
   .addToBackStack(null)
   .commit();
}

4.2. Chuyển đơn vị dp thành pixel

public static int convertDpToPixel(int dp) {
     Resources r = Resources.getSystem();
     return Math.round(dp * (r.getDisplayMetrics().densityDpi / 160f));
}

4.3. Lib Thư viện Utils

https://github.com/changer/android-utils
https://github.com/Trinea/android-common/tree/master/src/cn/trinea/android/common/util

4.4. Chạy nhạc MP3

- From local:
MediaPlayer song = MediaPlayer.create(MainActivity.this, R.raw.nuocmat); 
song.start();

Stop: 
onPause(); 
song.pause();

- From Internet:
  public void PlayNhacMp3(String url){
        //url = "http://khoapham.vn/download/vietnamoi.mp3";
        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

4.5. Đọc ghi file .txt

- Save file txt
FileOutputStream fos = openFileOutput("khoapham.txt", Context.MODE_PRIVATE); 
fos.write(noidung.getBytes());
fos.close()

- Read file txt
FileInputStream fis = openFileInput("khoapham.txt"); 
BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream(fis))); 
String line = ""; 
while( (line = br.readLine()) != null ){ 
txtvNoiDung.append(line); 
txtvNoiDung.append("\n"); 
}

4.6. Lấy kích thước màn hình thiết bị

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); 
int width = display.getWidth(); 
int height = display.getHeight(); 
int ori = display.getOrientation();

4.7. Chuyển file thành dạng byte[]

public byte[] FileLocal_To_Byte(String path){
        File file = new File(path);
        int size = (int) file.length();
        byte[] bytes = new byte[size];
        try {
            BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
            buf.read(bytes, 0, bytes.length);
            buf.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bytes;
}

4.8. Định dạng tiền tệ việt nam

    //Convert long to money type
    public static String formatNumber(long number) {
        if (number < 1000) {
            return String.valueOf(number);
        }
        try {
            NumberFormat formatter = new DecimalFormat("###,###");
            String resp = formatter.format(number);
            resp = resp.replaceAll(",", ".");
            return resp;
        } catch (Exception e) {
            return "";
        }
    }

4.9. Kiểm tra EditText rỗng

 public static  boolean isEmpty(EditText etText) {
        if (etText.getText().toString().trim().length() > 0) {
            return true;
        } else {
            etText.requestFocus();
            etText.setError("Vui lòng điền thông tin!");
            return false;
        }
    }

4.10. Lấy chuỗi String Resource 

    public static String getStringFromResources(Context context, int id) {
        return context.getResources().getString(id);
    }

4.11. Chuyển dữ liệu kiểu LONG thành DateTime

    public static String convertLongToDay(long timeStamp) {
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        Date date = new Date(timeStamp);
        return  dateFormat.format(date);
    }

4.12. Kiểm tra định dạng Email

public static boolean isEmailValid(String email) {
        boolean isValid = false;

        String expression = "[a-zA-Z0-9._-]+@[a-z]+(\\.+[a-z]+)+";
        CharSequence inputStr = email;

        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

4.13 Chuyển ngôn ngữ sử dụng google translate

Để đoạn chuyển ngôn ngữ:

Sự kiện Click gọi hàm changeLanguageByButtonClick('en') hoặc mã ngôn ngữ tương ứng

Để đoạn code JS và css xuống footer:

<div id="google_translate_element" style="display:none"></div>

<script type="text/javascript">
function googleTranslateElementInit() {
   new google.translate.TranslateElement({pageLanguage: "vi"}, 'google_translate_element');
}

function changeLanguageByButtonClick(language) {
  var selectField = document.querySelector("#google_translate_element select");
  for(var i=0; i < selectField.children.length; i++){
    var option = selectField.children[i];
    // find desired langauge and change the former language of the hidden selection-field 
    if(option.value==language){
       selectField.selectedIndex = i;
       // trigger change event afterwards to make google-lib translate this side
       selectField.dispatchEvent(new Event('change'));
       break;
    }
  }
}
</script>
<style type="text/css">
    .skiptranslate{display: none !important;}
    body{top: 0 !important;}
</style>

<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

Bạn vui lòng NHẤN [Lấy mã giảm giá] phía trên và gửi vào zalo : 0376.367.994 để được ưu đãi lớn hơn 50% chi phí làm web nhé bạn.