{"id":21340263,"url":"https://github.com/mnestorov/wp-snippets","last_synced_at":"2025-07-12T14:33:07.218Z","repository":{"id":111494065,"uuid":"168541071","full_name":"mnestorov/wp-snippets","owner":"mnestorov","description":"A compilation of WordPress / WooCommerce code snippets and functions for developers who wants to create their own themes.","archived":false,"fork":false,"pushed_at":"2023-11-30T10:04:52.000Z","size":218,"stargazers_count":4,"open_issues_count":0,"forks_count":3,"subscribers_count":1,"default_branch":"master","last_synced_at":"2023-12-01T10:38:44.572Z","etag":null,"topics":["snippets","woocommerce","woocommerce-snippet","wordpress","wordpress-snippets","wp","wp-snippets"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mnestorov.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2019-01-31T14:45:35.000Z","updated_at":"2023-11-30T14:01:20.000Z","dependencies_parsed_at":null,"dependency_job_id":"2b803b6f-7666-4341-98a1-393b8b694cfc","html_url":"https://github.com/mnestorov/wp-snippets","commit_stats":null,"previous_names":[],"tags_count":0,"template":null,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mnestorov%2Fwp-snippets","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mnestorov%2Fwp-snippets/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mnestorov%2Fwp-snippets/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mnestorov%2Fwp-snippets/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mnestorov","download_url":"https://codeload.github.com/mnestorov/wp-snippets/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225824950,"owners_count":17529905,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["snippets","woocommerce","woocommerce-snippet","wordpress","wordpress-snippets","wp","wp-snippets"],"created_at":"2024-11-22T00:49:53.453Z","updated_at":"2024-11-22T00:49:53.999Z","avatar_url":"https://github.com/mnestorov.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\u003ca href=\"https://laravel.com\" target=\"_blank\"\u003e\u003cimg src=\"https://raw.githubusercontent.com/github/explore/80688e429a7d4ef2fca1e82350fe8e3517d3494d/topics/wordpress/wordpress.png\" width=\"100\" alt=\"Laravel Logo\"\u003e\u003c/a\u003e\u003c/p\u003e\n\n# WordPress - Snippets\n\n![Licence](https://img.shields.io/badge/Unlicense-red)\n\n## Overview\n\nThis is a list of useful **WordPress** and **WooCommerce** code snippets and functions that I often reference to enhance or clean up my sites. \n\n**Note:** Please be careful and make backups!\n\n## WordPress\n\n- [Hide WordPress Update Nag To All But Admins](#hide-wordpress-update-nag-to-all-but-admins)\n- [Utilize Proper WordPress Titles](#utilize-proper-wordpress-titles)\n- [Create Custom WordPress Dashboard Widget](#create-custom-wordpress-dashboard-widget)\n- [Remove All Dashboard Widgets](#remove-all-dashboard-widgets)\n- [Include Navigation Menus](#include-navigation-menus)\n- [Insert Custom Login Logo](#insert-custom-login-logo)\n- [Modify Admin Footer Text](#modify-admin-footer-text)\n- [Enqueue Styles And Scripts](#enqueue-styles-and-scripts)\n- [Enqueue Google Fonts](#enqueue-google-fonts)\n- [Modify Excerpt Length](#modify-excerpt-length)\n- [Change Read More Link](#change-read-more-link)\n- [Change More Excerpt](#change-more-excerpt)\n- [Disable Emoji Mess](#disable-emoji-mess)\n- [Remove Comments](#remove-comments)\n- [Change Media Gallery URL](#change-media-gallery-url)\n- [Create Custom Thumbnail Size](#create-custom-thumbnail-size)\n- [Allow Additional File Formats For The Media Library](#allow-additional-file-formats-for-the-media-library)\n- [Add Categories For Attachments](#add-categories-for-attachments)\n- [Add Tags For Attachments](#add-tags-for-attachments)\n- [Add Custom Excerpt To Pages](#add-custom-excerpt-to-pages)\n- [Create A Global String](#create-a-global-string)\n- [Support Featured Images](#support-featured-images)\n- [Support Search Form](#support-search-form)\n- [Excluding pages from search](#excluding-pages-from-search)\n- [Disable XMLRPC](#disable-xmlrpcphp)\n- [Escape HTML In Posts](#escape-html-in-posts)\n- [Create Custom Global Settings](#create-custom-global-settings)\n- [Remove WordPress Admin Bar](#remove-wordpress-admin-bar)\n- [Add Open Graph Meta Tags](#add-open-graph-meta-tags)\n- [Add Custom Post Type](#add-custom-post-type)\n- [Implement Preconnect To Google Fonts In Themes](#implement-preconnect-to-google-fonts-in-themes)\n- [Add Thumbnail Column To Post Listing](#add-thumbnail-column-to-post-listing)\n- [Add Lead Class To First Paragraph](#add-lead-class-to-first-paragraph)\n- [Exclude Custom Post Type From Search](#exclude-custom-post-type-from-search)\n- [Remove Query String From Static Resources](#remove-query-string-from-static-resources)\n- [Disable Website Field From Comment Form](#disable-website-field-from-comment-form)\n- [Modify jQuery](#modify-jquery)\n- [Disable JSON Rest API](#disable-json-rest-api)\n- [Switch Post Type](#switch-post-type)\n- [PHP Logger](#php-logger)\n- [Always Show Second Bar In TinyMCE](#always-show-second-bar-in-tinymce)\n- [Remove Admin Menu Items Depending On User Role](#remove-admin-menu-items-depending-on-user-role)\n- [Remove Admin Menu Items Depending On Email Address (Domain)](#remove-admin-menu-items-depending-on-email-address-domain)\n- [Reorder Admin Menu Items](#reorder-admin-menu-items)\n- [Exclude A Category From WordPress Loops](#exclude-a-category-from-wordpress-loops)\n- [Disable The JQMIGRATE Warning Message](#disable-the-jqmigrate-warning-message)\n- [Disable Gutenberg From WordPress 5 Without A Plugin](#disable-gutenberg-from-wordpress-5-without-a-plugin)\n- [Disable Automatic Updates In WordPress](#disable-automatic-updates-in-wordpress)\n- [Disable Automatic WordPress Plugin Updates](#disable-automatic-wordpress-plugin-updates)\n- [Disable Automatic WordPress Theme Updates](#disable-automatic-wordpress-theme-updates)\n- [Cleanup Image Edits In WordPress](#cleanup-image-edits-in-wordpress)\n- [Specify The Number Of Post Revisions](#specify-the-number-of-post-revisions)\n- [Disable Post Revisions](#disable-post-revisions)\n- [Show Popular Posts Without Plugins](#show-popular-posts-without-plugins)\n- [Linking Images Within A Theme](#linking-images-within-a-theme)\n- [Display Different Menus To Logged-In Users](#display-different-menus-to-logged-in-users)\n- [Send Email To Admin If User Updated His Profile](#send-email-to-admin-if-user-updated-his-profile)\n- [Create New Custom Widget](#create-new-custom-widget)\n\n## WooCommerce\n\n- [Create A Message For Remaining Amount Of A Purchase For Free Delivery In WooCommerce](#create-a-message-for-remaining-amount-of-a-purchase-for-free-delivery-in-woocommerce)\n- [Change The Appearance Of A Foreign Currency In WooCommerce](#change-the-appearance-of-a-foreign-currency-in-woocommerce)\n- [Remove Specific Product Tabs In WooCommerce](#remove-specific-product-tabs-in-woocommerce)\n- [Add A Message To The Login Or Registration Form In WooCommerce](#add-a-message-to-the-login-or-registration-form-in-woocommerce)\n- [Display All Products Purchased By User Via Shortcode In WooCommerce](#display-all-products-purchased-by-user-via-shortcode-in-woocommerce)\n- [How To Add Custom Post Type To WooCommerce](#how-to-add-custom-post-type-to-woocommerce)\n- [How To Add A New Tab At My Account Page In WooCommerce](#how-to-add-a-new-tab-at-my-account-page-in-woocommerce)\n- [How To Reorder A Custom Tab At My Account Page In WooCommerce](#how-to-reorder-a-custom-tab-at-my-account-page-in-woocommerce)\n\n## Security\n\n- [Disable Theme Or Plugin Editor In WP Admin](#disable-theme-or-plugin-editor-in-wp-admin)\n- [Remove WordPress Version](#remove-wordpress-version)\n\n## Other\n\n- [Default robots.txt For WordPress](#default-robotstxt-for-wordpress)\n- [Simple .htaccess For WordPress](#simple-htaccess-for-wordpress)\n\n---\n\n## WordPress\n\n### Hide WordPress Update Nag To All But Admins\n\n```php\n/**\n * Hide WordPress update nag to all but admins\n */\nfunction hide_update_notice_to_all_but_admin() {\n    if ( !current_user_can( 'update_core' ) ) {\n        remove_action( 'admin_notices', 'update_nag', 3 );\n    }\n}\n\nadd_action( 'admin_head', 'hide_update_notice_to_all_but_admin', 1 );\n```\n\n### Utilize Proper WordPress Titles\n\nMake sure to remove the `\u003ctitle\u003e` tag from your header.\n\n```php\n/**\n * Utilize proper WordPress titles\n */\nadd_theme_support( 'title-tag' );\n```\n\n### Create Custom WordPress Dashboard Widget\n\n```php\n/**\n * Create custom WordPress dashboard widget\n */\nfunction dashboard_widget_function() {\n    echo '\n        \u003ch2\u003eCustom Dashboard Widget\u003c/h2\u003e\n        \u003cp\u003eCustom content here\u003c/p\u003e\n    ';\n}\n\nfunction add_dashboard_widgets() {\n    wp_add_dashboard_widget( 'custom_dashboard_widget', 'Custom Dashoard Widget', 'dashboard_widget_function' );\n}\n\nadd_action( 'wp_dashboard_setup', 'add_dashboard_widgets' );\n```\n\n### Remove All Dashboard Widgets\n\n```php\n/**\n * Remove all dashboard widgets\n */\nfunction remove_dashboard_widgets() {\n    global $wp_meta_boxes;\n    \n    unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press'] );\n    unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links'] );\n    unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now'] );\n    unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins'] );\n    unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_drafts'] );\n    unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments'] );\n    unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_primary'] );\n    unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary'] );\n\n    remove_meta_box( 'dashboard_activity', 'dashboard', 'normal' );\n}\n\nadd_action( 'wp_dashboard_setup', 'remove_dashboard_widgets' );\n```\n\n### Include Navigation Menus\n\n```php\n/** \n * Include navigation menus\n */\nfunction register_my_menu() {\n    register_nav_menu( 'nav-menu', __( 'Navigation Menu' ) );\n}\n\nadd_action( 'init', 'register_my_menu' );\n```\n\nInsert this where you want it to appear, and save the menu in **Appearance -\u003e Menus**.\n\n```php\nwp_nav_menu( array( 'theme_location' =\u003e 'nav-menu' ) );\n```\n\nHere's the code for multiple menus:\n\n```php\nfunction register_my_menus() {\n    register_nav_menus(\n        array(\n            'new-menu'      =\u003e __( 'New Menu' ),\n            'another-menu'  =\u003e __( 'Another Menu' ),\n            'an-extra-menu' =\u003e __( 'An Extra Menu' ),\n        )\n    );\n}\n\nadd_action( 'init', 'register_my_menus' );\n```\n\n### Insert Custom Login Logo\n\n```php\n/**\n * Insert custom login logo\n */\nfunction custom_login_logo() {\n    echo '\n        \u003cstyle\u003e\n            .login h1 a { \n                background-image: url(image.jpg) !important; \n                background-size: 234px 67px; \n                width:234px; \n                height:67px; \n                display:block; \n            }\n        \u003c/style\u003e\n    ';\n}\n\nadd_action( 'login_head', 'custom_login_logo' );\n```\n\n### Modify Admin Footer Text\n\n```php\n/**\n * Modify admin footer text\n */\nfunction modify_footer() {\n    echo 'Created by \u003ca href=\"mailto:you@example.com\"\u003eyou\u003c/a\u003e.';\n}\n\nadd_filter( 'admin_footer_text', 'modify_footer' );\n```\n\n### Enqueue Styles And Scripts\n\n```php\n/**\n * Enqueue styles and scripts\n */\nfunction custom_scripts() {\n    wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6' );\n    wp_enqueue_style( 'style', get_template_directory_uri() . '/css/style.css' );\n    wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '3.3.6', true );\n    wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js' );\n}\n\nadd_action( 'wp_enqueue_scripts', 'custom_scripts' );\n```\n\n### Enqueue Google Fonts\n\n```php\n/**\n * Enqueue Google Fonts\n */\nfunction google_fonts() {\n    wp_register_style( 'OpenSans', '//fonts.googleapis.com/css?family=Open+Sans:400,600,700,800' );\n    wp_enqueue_style( 'OpenSans' );\n}\n\nadd_action( 'wp_print_styles', 'google_fonts' );\n```\n\n### Modify Excerpt Length\n\n```php\n/**\n * Modify excerpt length\n */\nfunction custom_excerpt_length( $length ) {\n    return 25;\n}\n\nadd_filter( 'excerpt_length', 'custom_excerpt_length', 999 );\n```\n\n### Change Read More Link\n\n```php\n/**\n * Change Read More link\n */\nfunction custom_read_more_link() {\n    return '\u003ca href=\"' . get_permalink() . '\"\u003eRead More\u003c/a\u003e';\n}\n\nadd_filter( 'the_content_more_link', 'custom_read_more_link' );\n```\n\n### Change More Excerpt\n\n```php\n/**\n * Change More excerpt\n */\nfunction custom_more_excerpt( $more ) {\n    return '...';\n}\n\nadd_filter( 'excerpt_more', 'custom_more_excerpt' );\n```\n\n### Disable Emoji Mess\n\n```php\n/**\n * Disable Emoji mess\n */\nfunction disable_wp_emojicons() {\n    remove_action( 'admin_print_styles', 'print_emoji_styles' );\n    remove_action( 'wp_head', 'print_emoji_detection_script', 7 );\n    remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );\n    remove_action( 'wp_print_styles', 'print_emoji_styles' );\n    remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );\n    remove_filter( 'the_content_feed', 'wp_staticize_emoji' );\n    remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );\n    add_filter( 'tiny_mce_plugins', 'disable_emojicons_tinymce' );\n    add_filter( 'emoji_svg_url', '__return_false' );\n}\n\nadd_action( 'init', 'disable_wp_emojicons' );\n\nfunction disable_emojicons_tinymce( $plugins ) {\n    return is_array( $plugins ) ? array_diff( $plugins, array( 'wpemoji' ) ) : array();\n}\n```\n\n### Remove Comments\n\n```php\n/**\n * Remove comments\n */\n \n// Removes from admin menu\nfunction my_remove_admin_menus() {\n    remove_menu_page( 'edit-comments.php' );\n}\n\nadd_action( 'admin_menu', 'my_remove_admin_menus' );\n\n// Removes from post and pages\nfunction remove_comment_support() {\n    remove_post_type_support( 'post', 'comments' );\n    remove_post_type_support( 'page', 'comments' );\n}\n\nadd_action( 'init', 'remove_comment_support', 100 );\n\n// Removes from admin bar\nfunction mytheme_admin_bar_render() {\n    global $wp_admin_bar;\n    $wp_admin_bar-\u003eremove_menu( 'comments' );\n}\n\nadd_action( 'wp_before_admin_bar_render', 'mytheme_admin_bar_render' );\n```\n\n### Change Media Gallery URL\n\n```php\n/**\n * Change Media Gallery URL\n */\nif ( empty( get_option( 'upload_url_path' ) ) ) {\n    update_option( 'upload_url_path', 'http://assets.website.com/wp-content/uploads' );\n}\n```\n\nAlso, you can filter the option value before it's retrieved from the database, which is slightly better:\n\n```php\n/**\n * Change Media Gallery URL\n */\nadd_filter( 'pre_option_upload_url_path', function() {\n    return 'http://assets.website.com/wp-content/uploads';\n});\n```\n\n### Create Custom Thumbnail Size\n\n```php\n/**\n * Create custom thumbnail size\n */\nadd_image_size( 'custom-thumbnail', 250, 250, true );\n```\n\n**Retrieve Thumbnail**\n\n ```php\n $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post-\u003eID), 'custom-thumbnail' );\n\n echo $thumb[0]; \n ```\n \nSince WordPress 4.4.0, you can use:\n\n```php\nthe_post_thumbnail_url( $size );\n```\n\n### Allow Additional File Formats For the Media Library\n\n```php\n/**\n * This code allows you to upload the file formats ZIP, MOBI, PDF, and EPUB\n */\nfunction add_custom_mime_types( $mimes ) {\n    $new_file_types = array (\n        'zip'  =\u003e 'application/zip',\n        'mobi' =\u003e 'application/x-mobipocket-ebook',\n        'pdf'  =\u003e 'application/pdf',\n        'epub' =\u003e 'application/epub+zip'\n    );\n    \n    return array_merge( $mimes, $new_file_types );\n}\n\nadd_filter( 'upload_mimes', 'add_custom_mime_types' );\n```\n\n\n### Add Categories For Attachments\n\n```php\n/**\n * Add categories for attachments\n */\nfunction add_categories_for_attachments() {\n    register_taxonomy_for_object_type( 'category', 'attachment' );\n}\n\nadd_action( 'init' , 'add_categories_for_attachments' );\n```\n\n### Add Tags For Attachments\n\n```php\n/**\n * Add tags for attachments\n */\nfunction add_tags_for_attachments() {\n    register_taxonomy_for_object_type( 'post_tag', 'attachment' );\n}\n\nadd_action( 'init' , 'add_tags_for_attachments' );\n```\n\n### Add Custom Excerpt To Pages\n\n```php\n/**\n * Add custom excerpt to pages\n */\nfunction add_page_excerpt() {\n    add_post_type_support( 'page', array( 'excerpt' ) );\n}\n\nadd_action( 'init', 'add_page_excerpt' );\n```\n\n### Create A Global String\n\n```php\n/**\n * Create a global string\n */\nfunction global_string() {\n    return 'String';\n}\n```\n\n**Retrieve Field**\n\n```php\necho global_string();\n```\n\n### Support Featured Images\n\n```php\n/**\n * Support featured images\n */\nadd_theme_support( 'post-thumbnails' );\n```\n\n### Support Search Form\n\n```php\n/**\n * Support search form\n */\nadd_theme_support( 'html5', array( 'search-form' ) );\n```\n\n### Excluding Pages From Search\n\n```php\n/**\n * Excluding pages from search\n */\nfunction exclude_pages_from_search() {\n    global $wp_post_types;\n    $wp_post_types['page']-\u003eexclude_from_search = true;\n}\n\nadd_action( 'init', 'exclude_pages_from_search' );\n```\n\n### Disable xmlrpc.php\n\n```php\n/**\n * Disable xmlrpc.php\n */\n \nadd_filter( 'xmlrpc_enabled', '__return_false' );\nremove_action( 'wp_head', 'rsd_link' );\nremove_action( 'wp_head', 'wlwmanifest_link' );\n```\n\n### Escape HTML In Posts\n\n```php\n/**\n * Escape HTML in \u003ccode\u003e or \u003cpre\u003e\u003ccode\u003e tags.\n */\nfunction escapeHTML($arr) {\n    if (version_compare(PHP_VERSION, '5.2.3') \u003e= 0) {\n        $output = htmlspecialchars($arr[2], ENT_NOQUOTES, get_bloginfo('charset'), false);\n    } else {\n        $specialChars = array(\n            '\u0026' =\u003e '\u0026amp;',\n            '\u003c' =\u003e '\u0026lt;',\n            '\u003e' =\u003e '\u0026gt;'\n        );\n\n        // decode already converted data\n        $data = htmlspecialchars_decode( $arr[2] );\n        \n\t// escape all data inside \u003cpre\u003e\n        $output = strtr( $data, $specialChars );\n    }\n    \n    if (! empty($output)) {\n        return  $arr[1] . $output . $arr[3];\n    } else {\n        return  $arr[1] . $arr[2] . $arr[3];\n    }\n}\n\nfunction filterCode( $data ) { // Uncomment if you want to escape anything within a \u003cpre\u003e tag\n    //$modifiedData = preg_replace_callback( '@(\u003cpre.*\u003e)(.*)(\u003c\\/pre\u003e)@isU', 'escapeHTML', $data );\n    $modifiedData = preg_replace_callback( '@(\u003ccode.*\u003e)(.*)(\u003c\\/code\u003e)@isU', 'escapeHTML', $data );\n    $modifiedData = preg_replace_callback( '@(\u003ctt.*\u003e)(.*)(\u003c\\/tt\u003e)@isU', 'escapeHTML', $modifiedData );\n\n    return $modifiedData;\n}\n\nadd_filter( 'content_save_pre', 'filterCode', 9 );\nadd_filter( 'excerpt_save_pre', 'filterCode', 9 );\n```\n\nModified from [Escape HTML](https://wordpress.org/plugins/escape-html/).\n\n### Create Custom Global Settings\n\n```php\n/**\n * Create custom global settings\n */\nfunction custom_settings_page() { ?\u003e\n    \u003cdiv class=\"wrap\"\u003e\n    \u003ch1\u003eCustom Settings\u003c/h1\u003e\n    \u003cform method=\"post\" action=\"options.php\"\u003e\n        \u003c?php\n            settings_fields( 'section' );\n            do_settings_sections( 'theme-options' );\n            submit_button();\n        ?\u003e\n    \u003c/form\u003e\n    \u003c/div\u003e\u003c?php \n}\n\nfunction custom_settings_add_menu() {\n    add_theme_page( 'Custom Settings', 'Custom Settings', 'manage_options', 'custom-settings', 'custom_settings_page', null, 99 );\n}\n\nadd_action( 'admin_menu', 'custom_settings_add_menu' );\n\n// Example setting\nfunction setting_twitter() { ?\u003e\n    \u003cinput type=\"text\" name=\"twitter\" id=\"twitter\" value=\"\u003c?php echo get_option('twitter'); ?\u003e\" /\u003e\u003c?php \n}\n\nfunction custom_settings_page_setup() {\n    add_settings_section( 'section', 'All Settings', null, 'theme-options' );\n    add_settings_field( 'twitter', 'Twitter Username', 'setting_twitter', 'theme-options', 'section' );\n    register_setting( 'section', 'twitter' );\n}\n\nadd_action( 'admin_init', 'custom_settings_page_setup' );\n```\n\n**Retrieve Field**\n\n```php\necho get_option( 'twitter' );\n```\n\nModified from [Create a WordPress Theme Settings Page with the Settings API](http://www.sitepoint.com/create-a-wordpress-theme-settings-page-with-the-settings-api/).\n\n### Remove WordPress Admin Bar\n\n```php\n/**\n * Remove WordPress admin bar\n */\nfunction remove_admin_bar() {\n    remove_action( 'wp_head', '_admin_bar_bump_cb' );\n}\n\nadd_action( 'get_header', 'remove_admin_bar' );\n```\n\n### Add Open Graph Meta Tags\n\n```php\n/**\n * Add Open Graph Meta Tags\n */\nfunction meta_og() {\n    global $post;\n\n    if ( is_single() ) {\n        if( has_post_thumbnail( $post-\u003eID ) ) {\n            $img_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post-\u003eID ), 'thumbnail' );\n        } \n        $excerpt = strip_tags( $post-\u003epost_content );\n        $excerpt_more = '';\n\t\n        if ( strlen($excerpt ) \u003e 155) {\n            $excerpt = substr( $excerpt,0,155 );\n            $excerpt_more = ' ...';\n        }\n\t\n        $excerpt = str_replace( '\"', '', $excerpt );\n        $excerpt = str_replace( \"'\", '', $excerpt );\n        $excerptwords = preg_split( '/[\\n\\r\\t ]+/', $excerpt, -1, PREG_SPLIT_NO_EMPTY );\n        array_pop( $excerptwords );\n        $excerpt = implode( ' ', $excerptwords ) . $excerpt_more; ?\u003e\n\t\n        \u003cmeta name=\"author\" content=\"Your Name\"\u003e\n        \u003cmeta name=\"description\" content=\"\u003c?php echo $excerpt; ?\u003e\"\u003e\n        \u003cmeta property=\"og:title\" content=\"\u003c?php echo the_title(); ?\u003e\"\u003e\n        \u003cmeta property=\"og:description\" content=\"\u003c?php echo $excerpt; ?\u003e\"\u003e\n        \u003cmeta property=\"og:type\" content=\"article\"\u003e\n        \u003cmeta property=\"og:url\" content=\"\u003c?php echo the_permalink(); ?\u003e\"\u003e\n        \u003cmeta property=\"og:site_name\" content=\"Your Site Name\"\u003e\n        \u003cmeta property=\"og:image\" content=\"\u003c?php echo $img_src[0]; ?\u003e\"\u003e\u003c?php\n    } else {\n        return;\n    }\n}\n\nadd_action('wp_head', 'meta_og', 5);\n```\n\n### Add Custom Post Type\n\n```php\n/**\n * Add custom post type\n */\nfunction create_custom_post() {\n    register_post_type( 'custom-post', // slug for custom post type\n        array(\n        'labels' =\u003e array(\n            'name' =\u003e __( 'Custom Post' ),\n        ),\n        'public'       =\u003e true,\n        'hierarchical' =\u003e true, \n        'has_archive'  =\u003e true,\n        'supports'     =\u003e array(\n            'title',\n            'editor',\n            'excerpt',\n            'thumbnail',\n        ), \n        'can_export' =\u003e true,\n        'taxonomies' =\u003e array(\n             'post_tag',\n              category',\n        )\n    ));\n}\n\nadd_action( 'init', 'create_custom_post' );\n```\n\n**WordPress Codex**\n\n[Function Reference/register post type](https://codex.wordpress.org/Function_Reference/register_post_type)\n\n**WordPress Developer Resources**\n\n[Dashicons](https://developer.wordpress.org/resource/dashicons/#menu)\n\n### Implement Preconnect To Google Fonts In Themes\n\n```php\n/**\n * Implement preconnect to Google Fonts in themes\n */\nfunction twentyfifteen_resource_hints( $urls, $relation_type ) {\n    // Checks whether the subject is carrying the source of fonts google and the `$relation_type` equals preconnect.\n    // Replace `enqueue_font_id` the `ID` used in loading the source.\n    if ( wp_style_is( 'enqueue_font_id', 'queue' ) \u0026\u0026 'preconnect' === $relation_type ) {\n        // Checks whether the version of WordPress is greater than or equal to 4.7\n        // to ensure compatibility with older versions\n        // because the 4.7 has become necessary to return an array instead of string\n        \n\tif ( version_compare( $GLOBALS['wp_version'], '4.7-alpha', '\u003e=' ) ) {\n            // Array with url google fonts and crossorigin\n            $urls[] = array(\n                'href' =\u003e 'https://fonts.gstatic.com',\n                'crossorigin',\n            );\n        } else {\n            // String with url google fonts\n            $urls[] = 'https://fonts.gstatic.com';\n        }\n    }\n    \n    return $urls;\n}\n\nadd_filter( 'wp_resource_hints', 'twentyfifteen_resource_hints', 10, 2 ); \n```\n\n### Add Thumbnail Column To Post Listing\n\n```php\n/**\n * Add thumbnail column to post listing\n */\nadd_image_size( 'admin-list-thumb', 80, 80, false );\n\nfunction wpcs_add_thumbnail_columns( $columns ) {\n    if ( !is_array( $columns ) ) {\n        $columns = array();\n    }\n    \n    $new = array();\n\n    foreach( $columns as $key =\u003e $title ) {\n        if ( $key == 'title' ) { // Put the Thumbnail column before the Title column\n            $new['featured_thumb'] = __( 'Image');\n\t}\n\t\n        $new[$key] = $title;\n    }\n    \n    return $new;\n}\n\nfunction wpcs_add_thumbnail_columns_data( $column, $post_id ) {\n    switch ( $column ) {\n    case 'featured_thumb':\n        echo '\u003ca href=\"' . $post_id . '\"\u003e';\n        echo the_post_thumbnail( 'admin-list-thumb' );\n        echo '\u003c/a\u003e';\n        break;\n    }\n}\n\nif ( function_exists( 'add_theme_support' ) ) {\n    add_filter( 'manage_posts_columns' , 'wpcs_add_thumbnail_columns' );\n    add_action( 'manage_posts_custom_column' , 'wpcs_add_thumbnail_columns_data', 10, 2 );\n}\n```\n### Add Lead Class To First Paragraph\n\n```php\n/**\n * Add lead class to first paragraph\n */\nfunction first_paragraph( $content ) {\n    return preg_replace( '/\u003cp([^\u003e]+)?\u003e/', '\u003cp$1 class=\"lead\"\u003e', $content, 1 );\n}\n\nadd_filter( 'the_content', 'first_paragraph' );\n```\n\nAdds a `lead` class to the first paragraph in [the_content](https://developer.wordpress.org/reference/functions/the_content/).\n\n### Exclude Custom Post Type From Search\n\n```php\n/**\n * Exclude custom post type from search\n */\nfunction excludePages( $query ) {\n   if ( $query-\u003eis_search ) {\n      $query-\u003eset( 'post_type', 'post' );\n   }\n   return $query;\n}\n\nadd_filter( 'pre_get_posts','excludePages' );\n```\n\n### Remove Query String From Static Resources\n\n```php\n/**\n * Remove query string from static resources \n */\nfunction remove_cssjs_ver( $src ) {\n    if ( strpos( $src, '?ver=' ) ) {\n        $src = remove_query_arg( 'ver', $src );\n    }\n\t\n    return $src;\n}\n\nadd_filter( 'style_loader_src', 'remove_cssjs_ver', 10, 2 );\nadd_filter( 'script_loader_src', 'remove_cssjs_ver', 10, 2 );\n```\n\n### Modify jQuery\n\n```php\n/**\n * Modify jQuery\n */\nfunction modify_jquery() {\n    wp_deregister_script( 'jquery' );\n    wp_register_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', false, '3.2.1' );\n    wp_enqueue_script( 'jquery' );\n}\n\nif ( ! is_admin() ) add_action( 'wp_enqueue_scripts', 'modify_jquery' );\n```\n\n###  Disable Website Field From Comment Form\n\n```php\n/** \n * Disable website field from comment form\n */\nfunction disable_website_field( $field ) { \n    if( isset($field['url']) ) {\n        unset( $field['url'] );\n    }\n    \n    return $field;\n}\n\nadd_filter('comment_form_default_fields', 'disable_website_field');\n```\n\n###  Disable JSON REST API\n\n```php\n/** \n * Disable JSON REST API  \n */\nadd_filter( 'json_enabled', '__return_false' );\nadd_filter( 'json_jsonp_enabled', '__return_false' );\n```\n\n### Switch Post Type\n\n```php\n/**\n * Switch post type\n */\nfunction switch_post_type ( $old_post_type, $new_post_type ) {\n    global $wpdb;\n\n    // Run the update query\n    $wpdb-\u003eupdate(\n        $wpdb-\u003eposts,\n        // Set\n        array( 'post_type' =\u003e $new_post_type),\n        // Where\n        array( 'post_type' =\u003e $old_post_type )\n    );\n}\n```\n\n### PHP Logger\n\n```php\n/**\n * PHP Logger\n */\nfunction php_logger( $data ) {\n    $output = $data;\n    if ( is_array( $output ) )\n        $output = implode( ',', $output );\n        \n    // print the result into the JavaScript console\n    echo \"\u003cscript\u003econsole.log( 'PHP LOG: \" . $output . \"' );\u003c/script\u003e\";\n}\n```\n\n### Always Show Second Bar In TinyMCE\n\n```php\n/**\n * Always show second bar in TinyMCE\n */\nfunction show_tinymce_toolbar( $in ) {\n    $in['wordpress_adv_hidden'] = false;\n    return $in;\n}\n\nadd_filter( 'tiny_mce_before_init', 'show_tinymce_toolbar' );\n```\n\n### Remove Admin Menu Items Depending On User Role\n\n```php\n/**\n * Clone the administrator user role\n */\nfunction clone_admin_role() {\n    global $wp_roles;\n    if ( ! isset( $wp_roles ) )\n        $wp_roles = new WP_Roles();\n    \n    $adm = $wp_roles-\u003eget_role( 'administrator' );\n    \n    // Add new \"Client\" role with all admin capabilities\n    $wp_roles-\u003eadd_role( 'client', 'Client', $adm-\u003ecapabilities );\n}\n\nadd_action( 'init', 'clone_admin_role' );\n\n/**\n * Specify which admin menu items are visible for users with role \"Client\"\n */\nfunction remove_dashboard_menus() {\n    if ( current_user_can( 'client' ) ) {\n        // Hide Updates under Dashboard menu\n        remove_submenu_page( 'index.php', 'update-core.php' );\n\n        // Hide Comments\n        remove_menu_page( 'edit-comments.php' );\n\n        // Hide Plugins\n        remove_menu_page( 'plugins.php' );\n\n        // Hide Themes, Customizer and Widgets under Appearance menu\n        remove_submenu_page( 'themes.php', 'themes.php' );\n        remove_submenu_page( 'themes.php', 'customize.php?return=' . urlencode( $_SERVER['REQUEST_URI'] ) );\n        remove_submenu_page( 'themes.php', 'widgets.php' );\n\n        // Hide Tools\n        remove_menu_page( 'tools.php' );\n\n        // Hide General Settings\n        remove_menu_page( 'options-general.php' );\n    }\n}\n\nadd_action( 'admin_menu', 'remove_dashboard_menus' );\n```\n\n### Remove Admin Menu Items Depending On Email Address (domain)\n\n```php\n/**\n * Specify which users can see admin menu items based on their email address\n */\nfunction remove_dashboard_menus() {\n    $user_data = get_userdata( get_current_user_id() );\n    $user_email = isset( $user_data-\u003euser_email ) ? $user_data-\u003euser_email : '';\n\n    if ( ! strpos( $user_email, '@yourcompany.com' ) ) {\n        // Hide Updates under Dashboard menu\n        remove_submenu_page( 'index.php', 'update-core.php' );\n\n        // Hide Comments\n        remove_menu_page( 'edit-comments.php' );\n\n        // Hide Plugins\n        remove_menu_page( 'plugins.php' );\n\n        // Hide Themes, Customizer and Widgets under Appearance menu\n        remove_submenu_page( 'themes.php', 'themes.php' );\n        remove_submenu_page( 'themes.php', 'customize.php?return=' . urlencode( $_SERVER['REQUEST_URI'] ) );\n        remove_submenu_page( 'themes.php', 'widgets.php' );\n\n        // Hide Tools\n        remove_menu_page( 'tools.php' );\n\n        // Hide General Settings\n        remove_menu_page( 'options-general.php' );\n    }\n}\n\nadd_action( 'admin_menu', 'remove_dashboard_menus' );\n```\n\n### Reorder Admin Menu Items\n\n```php\n/**\n * Reorder the Admin Menu\n */\nfunction custom_menu_order( $menu_ord ) {\n    if ( ! $menu_ord ) { return true; }\n        return array(\n            'index.php',\n            'separator1',\n            'edit.php?post_type=page', \n            'edit.php', \n            'edit.php?post_type=[your_post_type_slug]',\n            'upload.php',\n            'edit-comments.php',\n            'separator2',\n            'themes.php',\n            'plugins.php',\n            'users.php',\n            'tools.php',\n            'options-general.php'\n        );\n    }\n}\n\nadd_filter( 'custom_menu_order', 'custom_menu_order' );\nadd_filter( 'menu_order', 'custom_menu_order' );\n```\n\n### Exclude A Category From WordPress Loops\n\n```php\n/**\n * Exclude a category from all WordPress loops\n */\nadd_action( 'pre_get_posts', function( $query ) { // anonymous callback\n    \n    global $wp_query; \n\n    // Hard coded category ID, but can be dynamic: esc_attr(get_option('your-cat-id')); \n    $excluded_cat_id = 25;\n\n    // add category ID to existing, avoid overwriting it \n    $cat[] = $query-\u003eget( 'cat' );\n    $cat[] = \"-\" . $excluded_cat_id;\n\n    $query-\u003eset( 'cat', $cat );\n    }\n});\n```\n\n### Disable The JQMIGRATE Warning Message\n\n```php\n/**\n * Disable the message \"JQMIGRATE: Migrate is installed version 1.4.1\"\n */\nadd_action('wp_default_scripts', function ($scripts) {\n    if (!empty($scripts-\u003eregistered['jquery'])) {\n        $scripts-\u003eregistered['jquery']-\u003edeps = array_diff($scripts-\u003eregistered['jquery']-\u003edeps, ['jquery-migrate']);\n    }\n});\n```\n\n### Disable Gutenberg From WordPress 5 Without A Plugin\n\n```php\nadd_filter( 'use_block_editor_for_post', '__return_false' );\n```\n\n### Disable Automatic Updates In WordPress\n\n```php\ndefine( 'WP_AUTO_UPDATE_CORE', false );\n```\n\n**How to implement**\n\nYou can disable automatic updates in WordPress by adding this line of code in your **_wp-config.php_**.\n\n### Disable Automatic WordPress Plugin Updates\n\n```php\nadd_filter( 'auto_update_plugin', '__return_false' );\n```\n\n### Disable Automatic WordPress Theme Updates\n\n```php\nadd_filter( 'auto_update_theme', '__return_false' );\n```\n\n### Cleanup Image Edits In WordPress\n\n```php\ndefine( 'IMAGE_EDIT_OVERWRITE', true );\n```\n\nBy default, WordPress creates a new set of images every time an image is edited. When you restore the original image, the edits are stored on the server. Defining **_IMAGE_EDIT_OVERWRITE_** as **_true_** changes this behaviour. Only one set of image edits are ever created and when you restore the original, the edits are removed from the server.\n\n**How to implement**\n\nYou can define cleanup image edits in WordPress by adding this line of code in your **_wp-config.php_**.\n\n### Specify The Number Of Post Revisions\n\n```php\ndefine('WP_POST_REVISIONS', 3);\n```\n\nIf you want to specify a maximum number of revisions, change false to an integer/number (e.g., 3 or 5).\n\n**How to implement**\n\nYou can specify the number of post revisions in WordPress by adding this line of code in your **_wp-config.php_**.\n\n### Disable Post Revisions\n\n```php\ndefine( 'WP_POST_REVISIONS', false );\n```\n\nBy default, WordPress will save copies of each edit made to a post or page, allowing the possibility of reverting to a previous version of that post or page. The saving of revisions can be disabled, or a maximum number of revisions per post or page can be specified.\n\n**How to implement**\n\nYou can disable post revisions in WordPress by adding this line of code in your **_wp-config.php_**.\n\n### Show Popular Posts Without Plugins\n\n```php\n/**\n * Show Popular Posts Without Plugins\n */\nfunction count_post_visits() {\n    if( is_single() ) {\n        global $post;\n        $views = get_post_meta( $post-\u003eID, 'my_post_viewed', true );\n        if( $views == '' ) {\n            update_post_meta( $post-\u003eID, 'my_post_viewed', '1' );   \n        } else {\n            $views_no = intval( $views );\n            update_post_meta( $post-\u003eID, 'my_post_viewed', ++$views_no );\n        }\n    }\n}\n\nadd_action( 'wp_head', 'count_post_visits' );\n```\n\n### Linking Images Within A Theme\n\n```php\n\u003cimg src=\"\u003c?php bloginfo( 'stylesheet_directory' ); ?\u003e/img/image.png\" /\u003e\n```\n\nor\n\n```php\n\u003cimg src=\"\u003c?php echo get_stylesheet_directory_uri(); ?\u003e/images/image.jpg\" /\u003e\n```\n\n### Display Different Menus To Logged-In Users\n\n```php\nfunction nav_menu_args( $args = '' ) {\n    if ( is_user_logged_in() ) {\n        $args['menu'] = 'Logged-In'; // we need to create this menu\n    } else {\n        $args['menu'] = 'Primary Menu'; // we need to create this menu\n    }\n\n    return $args;\n}\n\nadd_filter( 'wp_nav_menu_args', 'nav_menu_args' );\n```\n\n### Send Email To Admin If User Updated His Profile\n\n```php\nfunction user_profile_update( $user_id ) {\n    $user_info = get_userdata( $user_id );\n\n    $to       = get_option( 'admin_email' );\n    $subject  = 'User Profile Updated';\n    $message  = \"Hello Administrator,\\n\\nThe \" . $user_info-\u003euser_nicename . \" (\" . $user_info-\u003euser_email . \") profile has been updated! \\n\\n\";\n    $message .= \"Site URL: \" . get_bloginfo( 'wpurl' ) . \"\\n\\n\";\n    $message .= \"Regards, \\n\" . get_option( 'blogname' );\n\n    wp_mail( $to, $subject, $message );\n}\n\nadd_action( 'profile_update', 'user_profile_update', 10, 2 );\n```\n\n### Create New Custom Widget\n\n```php\nclass New_Widget extends WP_Widget {\n\n\tfunction __construct() {\n\t\tparent::__construct(\n\t\t\t'new_widget',\n\t\t\tesc_html__( 'Widget', 'textdomain' )\n\t\t);\n\t}\n\n\tprivate $widget_fields = array(\n\t);\n\n\tpublic function widget( $args, $instance ) {\n\t\techo $args['before_widget'];\n\n\t\tif ( ! empty( $instance['title'] ) ) {\n\t\t\techo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];\n\t\t}\n\n\t\t// Output generated fields\n\t\t\n\t\techo $args['after_widget'];\n\t}\n\n\tpublic function field_generator( $instance ) {\n\t\t$output = '';\n\t\tforeach ( $this-\u003ewidget_fields as $widget_field ) {\n\t\t\t$default = '';\n\t\t\tif ( isset($widget_field['default']) ) {\n\t\t\t\t$default = $widget_field['default'];\n\t\t\t}\n\t\t\t$widget_value = ! empty( $instance[$widget_field['id']] ) ? $instance[$widget_field['id']] : esc_html__( $default, 'textdomain' );\n\t\t\tswitch ( $widget_field['type'] ) {\n\t\t\t\tdefault:\n\t\t\t\t\t$output .= '\u003cp\u003e';\n\t\t\t\t\t$output .= '\u003clabel for=\"'.esc_attr( $this-\u003eget_field_id( $widget_field['id'] ) ).'\"\u003e'.esc_attr( $widget_field['label'], 'textdomain' ).':\u003c/label\u003e ';\n\t\t\t\t\t$output .= '\u003cinput class=\"widefat\" id=\"'.esc_attr( $this-\u003eget_field_id( $widget_field['id'] ) ).'\" name=\"'.esc_attr( $this-\u003eget_field_name( $widget_field['id'] ) ).'\" type=\"'.$widget_field['type'].'\" value=\"'.esc_attr( $widget_value ).'\"\u003e';\n\t\t\t\t\t$output .= '\u003c/p\u003e';\n\t\t\t}\n\t\t}\n\t\techo $output;\n\t}\n\n\tpublic function form( $instance ) {\n\t\t$title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( '', 'textdomain' );\n\t\t?\u003e\n\t\t\u003cp\u003e\n\t\t\t\u003clabel for=\"\u003c?php echo esc_attr( $this-\u003eget_field_id( 'title' ) ); ?\u003e\"\u003e\u003c?php esc_attr_e( 'Title:', 'textdomain' ); ?\u003e\u003c/label\u003e\n\t\t\t\u003cinput class=\"widefat\" id=\"\u003c?php echo esc_attr( $this-\u003eget_field_id( 'title' ) ); ?\u003e\" name=\"\u003c?php echo esc_attr( $this-\u003eget_field_name( 'title' ) ); ?\u003e\" type=\"text\" value=\"\u003c?php echo esc_attr( $title ); ?\u003e\"\u003e\n\t\t\u003c/p\u003e\n\t\t\u003c?php\n\t\t$this-\u003efield_generator( $instance );\n\t}\n\n\tpublic function update( $new_instance, $old_instance ) {\n\t\t$instance = array();\n\t\t$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';\n\t\tforeach ( $this-\u003ewidget_fields as $widget_field ) {\n\t\t\tswitch ( $widget_field['type'] ) {\n\t\t\t\tdefault:\n\t\t\t\t\t$instance[$widget_field['id']] = ( ! empty( $new_instance[$widget_field['id']] ) ) ? strip_tags( $new_instance[$widget_field['id']] ) : '';\n\t\t\t}\n\t\t}\n\t\treturn $instance;\n\t}\n}\n\nfunction register_new_widget() {\n\tregister_widget( 'New_Widget' );\n}\nadd_action( 'widgets_init', 'register_new_widget' );\n```\n\n## WooCommerce\n\n### Change The Appearance Of A Foreign Currency In WooCommerce\n\n```php\nfunction wc_change_bgn_currency_symbol( $currency_symbol, $currency ) {\n  switch ( $currency ) {\n    case 'BGN':\n      $currency_symbol = 'BGN';\n    break;\n  }\n  \n  return $currency_symbol;\n}\n\nadd_filter( 'woocommerce_currency_symbol', 'wc_change_bgn_currency_symbol', 10, 2 );\n```\n\n### Create A Message For Remaining Amount Of A Purchase For Free Delivery In WooCommerce\n\n```php\n/**\n * Notice with $$$ remaining to Free Shipping @ WooCommerce Cart \n * Tested with WooCommerce version 3.0.5\n */ \nfunction wc_free_shipping_cart_notice() { \n  global $woocommerce; \n  // Get Free Shipping Methods for Rest of the World Zone \u0026 populate array $min_amounts\n  $default_zone = new WC_Shipping_Zone(0); \n  $default_methods = $default_zone-\u003eget_shipping_methods();\n    foreach( $default_methods as $key =\u003e $value ) {\n      if ( $value-\u003eid === \"free_shipping\" ) {\n        if ( $value-\u003emin_amount \u003e 0 ) $min_amounts[] = $value-\u003emin_amount;\n      }\n    }\n    \n    // Get Free Shipping Methods for all other ZONES \u0026 populate array $min_amounts\n    $delivery_zones = WC_Shipping_Zones::get_zones();\n    foreach ( $delivery_zones as $key =\u003e $delivery_zone ) {\n      foreach ( $delivery_zone['shipping_methods'] as $key =\u003e $value ) {\n        if ( $value-\u003eid === \"free_shipping\" ) {\n          if ( $value-\u003emin_amount \u003e 0 ) $min_amounts[] = $value-\u003emin_amount;\n        }\n      }\n    }\n    \n    // Find lowest min_amount\n    if ( is_array($min_amounts) ) {\n       $min_amount = min($min_amounts);\n       // Get Cart Subtotal inc. Tax excl. Shipping\n       $current = WC()-\u003ecart-\u003esubtotal;\n       // If Subtotal \u003c Min Amount, еcho Notice and add \"Continue Shopping\" button\n       if ( $current \u003c $min_amount ) {\n          $added_text = esc_html__('You need to add ', 'woocommerce' ) . wc_price( $min_amount - $current ) . esc_html__(' for free delivery!', 'woocommerce' );\n    $return_to = apply_filters( 'woocommerce_continue_shopping_redirect', wc_get_raw_referer() ? wp_validate_redirect( wc_get_raw_referer(), false ) : wc_get_page_permalink( '/' ) );\n    $notice = sprintf( '%s %s', esc_url( $return_to ), esc_html__( 'Continue shopping', 'woocommerce' ), $added_text );\n    wc_print_notice( $notice, 'notice' );\n       }\n    }\n}\n\nadd_action( 'woocommerce_before_cart', 'wc_free_shipping_cart_notice' );\n```\n\n### Remove Specific Product Tabs In WooCommerce\n\n```php\nfunction wc_remove_product_tabs( $tabs ) {\n   // remove the description tab\n   unset( $tabs['description'] );\n   \n   // remove the reviews tab\n   unset( $tabs['reviews'] );\n   \n   // remove the additional information tab\n   unset( $tabs['additional_information'] );\n   \n   return $tabs;\n}\n\nadd_filter( 'woocommerce_product_tabs', 'wc_remove_product_tabs', 99 );\n```\n\n### Add A Message To The Login Or Registration Form In WooCommerce\n\n```php\nfunction wc_custom_login_message() {\n   if ( get_option( 'woocommerce_enable_myaccount_registration' ) == 'yes' ) {\n       $html  = '\u003cdiv class=\"woocommerce-info\"\u003e';\n       $html .= '\u003cp\u003e' . _e( 'Your custom message goes here.' ) . '\u003c/p\u003e';\n       $html .= '\u003c/div\u003e';\n       echo $html;\n   }\n}\n\nadd_action( 'woocommerce_before_customer_login_form', 'wc_custom_login_message' );\n```\n\n### Display All Products Purchased By User Via Shortcode In WooCommerce\n\n```php \nadd_shortcode( 'my_products', 'wc_user_products_bought' );\n  \nfunction wc_user_products_bought() {\n  \n    global $product, $woocommerce, $woocommerce_loop;\n    $columns = 3;\n  \n    // Get user\n    $current_user = wp_get_current_user();\n  \n    // Get user orders (COMPLETED + PROCESSING)\n    $customer_orders = get_posts( array(\n        'numberposts' =\u003e -1,\n        'meta_key'    =\u003e '_customer_user',\n        'meta_value'  =\u003e $current_user-\u003eID,\n        'post_type'   =\u003e wc_get_order_types(),\n        'post_status' =\u003e array_keys( wc_get_is_paid_statuses() ),\n    ) );\n  \n    // Loop Through orders and get product IDs\n    if ( ! $customer_orders ) return;\n    \n    $product_ids = array();\n    \n    foreach ( $customer_orders as $customer_order ) {\n        $order = wc_get_order( $customer_order-\u003eID );\n        $items = $order-\u003eget_items();\n        foreach ( $items as $item ) {\n            $product_id = $item-\u003eget_product_id();\n            $product_ids[] = $product_id;\n        }\n    }\n    $product_ids = array_unique( $product_ids );\n  \n    // Query products\n    $args = array(\n       'post_type' =\u003e 'product',\n       'post__in' =\u003e $product_ids,\n    );\n    \n    $loop = new WP_Query( $args );\n  \n    // Generate WC loop\n    ob_start();\n    woocommerce_product_loop_start();\n    while ( $loop-\u003ehave_posts() ) : $loop-\u003ethe_post();\n    wc_get_template_part( 'content', 'product' ); \n    endwhile; \n    woocommerce_product_loop_end();\n    woocommerce_reset_loop();\n    wp_reset_postdata();\n  \n    // Return content\n    return '\u003cdiv class=\"woocommerce columns-' . $columns . '\"\u003e' . ob_get_clean() . '\u003c/div\u003e';\n}\n```\n\n### How To Add Custom Post Type To WooCommerce\n\n**Step 1**\n\n```php\n/**\n * Your post type should have a custom field called 'price'. \n * We just have to make sure that its meta key is '_price'. \n * How to check that? You can try to inspect the element:  \n * 1) Visit your post type admin page. \n * 2) Try to add or edit a post in your post type admin page. \n * 3) Look for the text box that has the price label and right click on the text box. \n * 4) You should find it's name attribute to be '_price'. \n * Usually the name is the meta key for a custom field.\n *\n * Add the code below if your meta key is not '_price'\n */\nadd_filter('woocommerce_get_price','wc_get_price', 20, 2);\n\nfunction wc_get_price($price, $post) {\n  if ($post-\u003epost-\u003epost_type === 'post') {\n    $price = get_post_meta($post-\u003eid, 'price', true);\n  }\n  \n  return $price;\n}\n```\n\n**Step 2**\n\n```php\n/**\n * You're now able to add a custom post type to the cart.\n * Now we have to create our own \"Add to Cart\" button.\n */\nadd_filter('the_content', 'wc_add_to_cart_button', 20, 1);\n\nfunction wc_add_to_cart_button($content) {\n  global $post;\n \n  if ($post-\u003epost_type !== 'post') {\n    return $content;\n  }\n\n  ob_start(); ?\u003e\n \n  \u003cform action=\"\" method=\"post\"\u003e\n    \u003cinput name=\"add-to-cart\" type=\"hidden\" value=\"\u003c?php echo $post-\u003eID ?\u003e\"\u003e\n    \u003cinput name=\"quantity\" type=\"number\" value=\"1\" min=\"1\"\u003e\n    \u003cinput name=\"submit\" type=\"submit\" value=\"Add to cart\u003e\n  \u003c/form\u003e\u003c?php\n\t\n  return $content . ob_get_clean();\n}\n```\n\n**Note:** You have to call `wc_print_notices()` function in your `single-{post_type}.php`. This will display the messages like: **\"'Hello world!' has been added to your cart.\"**.\n\n### How To Add A New Tab At My Account Page In WooCommerce\n\n```php\n/**\n * Register new endpoint slug to use for My Account page\n */\n\n/**\n * @important-note\tResave permalinks or it will give 404 error\n */\nfunction woo_custom_add_premium_support_endpoint() {\n   add_rewrite_endpoint( 'premium-support', EP_ROOT | EP_PAGES );\n}\n  \nadd_action( 'init', 'woo_custom_add_premium_support_endpoint' );\n  \n/**\n * Add new query var\n */\n  \nfunction woo_custom_premium_support_query_vars( $vars ) {\n   $vars[] = 'premium-support';\n   return $vars;\n}\n  \nadd_filter( 'woocommerce_get_query_vars', 'woo_custom_premium_support_query_vars', 0 );\n  \n/**\n * Insert the new endpoint into the My Account menu\n */\nfunction woo_custom_add_premium_support_link_my_account( $items ) {\n   $items['premium-support'] = 'Premium Support';\n   return $items;\n}\n  \nadd_filter( 'woocommerce_account_menu_items', 'woo_custom_add_premium_support_link_my_account' );\n  \n/**\n * Add content to the new endpoint\n */\nfunction woo_custom_premium_support_content() {\n   echo '\u003ch3\u003ePremium WooCommerce Support\u003c/h3\u003e\u003cp\u003eWelcome to the WooCommerce support area.\u003c/p\u003e';\n   echo do_shortcode( ' /* your shortcode here */ ' );\n}\n\n/**\n * @important-note\t\"add_action\" must follow 'woocommerce_account_{your-endpoint-slug}_endpoint' format\n */\nadd_action( 'woocommerce_account_premium-support_endpoint', 'woo_custom_premium_support_content' );\n```\n\n### How To Reorder A Custom Tab At My Account Page In WooCommerce\n\n```php\n/**\n * Rename or re-order my account menu items\n */\nfunction woo_reorder_my_account_menu() {\n    $neworder = array(\n        'dashboard'          =\u003e __( 'Dashboard', 'woocommerce' ),\n        'orders'             =\u003e __( 'Previous Orders', 'woocommerce' ),\n        'custom-tab'         =\u003e __( 'Custom Tab', 'woocommerce' ),\n        'edit-address'       =\u003e __( 'Addresses', 'woocommerce' ),\n        'edit-account'       =\u003e __( 'Account Details', 'woocommerce' ),\n        'customer-logout'    =\u003e __( 'Logout', 'woocommerce' ),\n    );\n    \n    return $neworder;\n}\n\nadd_filter ( 'woocommerce_account_menu_items', 'woo_reorder_my_account_menu' );\n```\n\n## Security\n\n### Disable Theme Or Plugin Editor In WP Admin\n\n```php \ndefine( 'DISALLOW_FILE_EDIT', true ); \n```\n\n**How to implement**\n\n1. Locate the file **_wp-config.php_** in the base directory of your WordPress directory.\n2. Open the file in a text editor.\n3. Past the code above to the end of this file.\n4. Save and close.\n\n### Remove WordPress Version\n\n```php \n/**\n * Remove WordPress version.\n * Better to hide it and keep hackers in the dark.\n */\nfunction remove_wp_version() {\n    return '';\n}\nadd_filter( 'the_generator', 'remove_wp_version' );\n```\n\n## Other\n\n### Default robots.txt For WordPress\n\n```txt\nUser-Agent: *\nAllow: /wp-content/uploads/\nDisallow: /wp-content/plugins/\nDisallow: /wp-content/themes/\nDisallow: /readme.html\nDisallow: /?s=\nDisallow: /search/\n\nSitemap: http://www.sitename.com/post-sitemap.xml\nSitemap: http://www.sitename.com/page-sitemap.xml\n```\n\n**How to Implement:**\n\n1. Create a file named **_robots.txt_**.\n2. Copy and paste the snippet above to the file.\n3. Switch the placeholder information with your unique address and save the file.\n4. Drop the file in your root directory for your website.\n\n### Simple .htaccess For WordPress\n\n```txt\n# BEGIN WordPress\n\u003cIfModule mod_rewrite.c\u003e\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n\u003c/IfModule\u003e\n# END WordPress\n```\n\n**How to Implement:**\n\n1. Backup your current **_.htaccess_** file.\n2. Edit a copy of the file and delete the current information.\n3. Copy and paste the snippet above to the file.\n4. Save the file.\n\n---\n\n## License\n\nThis repository is unlicense[d], so feel free to fork.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmnestorov%2Fwp-snippets","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmnestorov%2Fwp-snippets","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmnestorov%2Fwp-snippets/lists"}