Skip to content

Instantly share code, notes, and snippets.

@riipandi
Last active June 27, 2023 20:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save riipandi/ddfb83b8369d50fa2759f1b27f4a2587 to your computer and use it in GitHub Desktop.
Save riipandi/ddfb83b8369d50fa2759f1b27f4a2587 to your computer and use it in GitHub Desktop.
WordPress Snippets
<?php defined( 'ABSPATH' ) or die( 'No script kiddies please!' );
/*
* Plugin Name: Optimator
* Plugin URI: https://aris.web.id/
* Description: Some basic WordPress configuration optimization to make it better than default. This plugin contains other simplified plugins and snippets.
* Author: Aris Ripandi
* Author URI: https://aris.web.id/
* Version: 1.0
* License: GPLv3
* Text Domain: optimator
* Info: You can put this plugin into /wp-content/mu-plugins directory if you want to executed automatically.
*/
// Add some links on plugin page
function wpcore_settings_link( $links ) {
array_unshift( $links, '<a href="https://aris.web.id">Author</a>' );
array_unshift( $links, '<a href="https://twitter.com/riipandi">Feedback</a>' );
return $links;
}
$plugin = plugin_basename(__FILE__);
add_filter( "plugin_action_links_$plugin", "wpcore_settings_link" );
// Set Default Admin Color Scheme and Remove Admin Color Scheme Options
remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker');
remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker');
function awp_set_admin_color( $result ) {
return 'light'; // default, light, blue, coffee, ectoplasm, midnight, ocean, sunrise
}
add_filter( 'get_user_option_admin_color', 'awp_set_admin_color' );
// Remove Screen Options except Administrator
function wpb_remove_screen_options() {
if(!current_user_can('manage_options')) {
return false;
}
return true;
}
add_filter('screen_options_show_screen', 'wpb_remove_screen_options');
// Remove Query String
// https://kinsta.com/knowledgebase/remove-query-strings-static-resources/
function awp_remove_script_version( $src ){
$parts = explode( '?', $src );
return $parts[0];
}
add_filter( 'script_loader_src', 'awp_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', 'awp_remove_script_version', 15, 1 );
// Remove Meta Generator
function wpbeginner_remove_version() {
return '';
}
add_filter('the_generator', 'wpbeginner_remove_version');
// Disable XML-RPC
//add_filter('xmlrpc_enabled', '__return_false');
// Disable Pingback
function no_self_ping( &$links ) {
$home = get_option( 'home' );
foreach ( $links as $l => $link )
if ( 0 === strpos( $link, $home ) )
unset($links[$l]);
}
add_action( 'pre_ping', 'no_self_ping' );
// Disable Post by Email
add_filter('enable_post_by_email_configuration', '__return_false');
// Remove Welcome Panel
remove_action('welcome_panel', 'wp_welcome_panel');
// Hide Help Panel
function awp_remove_help_tabs( $old_help, $screen_id, $screen ){
$screen->remove_help_tabs();
return $old_help;
}
add_filter( 'contextual_help', 'awp_remove_help_tabs', 999, 3 );
// Enabe Automatic Update Themes and Plugins
add_filter( 'auto_update_plugin', '__return_true' );
add_filter( 'auto_update_theme', '__return_true' );
// Disable Automatic Update Email Notification
function wpb_stop_update_emails( $send, $type, $core_update, $result ) {
if ( ! empty( $type ) && $type == 'success' ) {
return false;
}
return true;
}
add_filter( 'auto_core_update_send_email', 'wpb_stop_auto_update_emails', 10, 4 );
// Remove URL Field on Comment
function disable_comment_url($fields) {
if ( isset( $fields['url'] ) ) { unset($fields['url']); }
if ( isset( $fields['fields']['url'] ) ) { unset($fields['fields']['url']); }
return $fields;
}
add_filter('comment_form_default_fields', 'disable_comment_url');
// Disable Comments on Attachments
function disable_comments_on_attachments( $open, $post_id ) {
$post = get_post( $post_id );
if( $post->post_type == 'attachment' ) {
return false;
}
return $open;
}
add_filter( 'comments_open', 'disable_comments_on_attachments', 10 , 2 );
// Moving the Comment Text Field to Bottom
function wpb_move_comment_field_to_bottom( $fields ) {
$comment_field = $fields['comment'];
unset( $fields['comment'] );
$fields['comment'] = $comment_field;
return $fields;
}
add_filter( 'comment_form_fields', 'wpb_move_comment_field_to_bottom' );
// Hiding Password Protected Posts in WordPress
function wpb_password_post_filter( $where = '' ) {
if (!is_single() && !current_user_can('edit_private_posts') && !is_admin()) {
$where .= " AND post_password = ''";
}
return $where;
}
add_filter( 'posts_where', 'wpb_password_post_filter' );
// Customize WP Admin Toolbar
function custom_toolbar($wp_admin_bar) {
$args = array(
'id' => 'wpbeginner',
'title' => 'Custom Search',
'href' => 'https://www.google.com:443/cse/publicurl?cx=014650714884974928014:oga60h37xim',
'meta' => array(
'class' => 'wpbeginner',
'title' => 'Google Custom Search Engine'
)
);
//$wp_admin_bar->add_node($args);
$wp_admin_bar->remove_node( 'wp-logo' );
}
add_action('admin_bawp_menu', 'custom_toolbar', 999);
// Change The Admin Footer Text
function custom_footer_admin () {
$text = 'Powered by <a href="http://wordpress.org/" target="_new">WordPress</a>';
$text .= '&nbsp;|&nbsp;';
$text .= 'Developed by <a href="https://aris.web.id/" target="_new">Aris Ripandi</a>';
echo $text;
}
add_filter('admin_footer_text', 'custom_footer_admin');
/* Cookie Bar
function cookie_bar() {
echo '<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/cookie-bar/cookiebar-latest.min.js?forceLang=en&tracking=1&thirdparty=1&always=1&noGeoIp=1&bottom=1&hideDetailsBtn=1&privacyPage=%2Fprivacy"></script>';
}
add_action( 'wp_footer', 'cookie_bar', 10 );
*/
// Remove the Login Shake Effect
function wpb_remove_loginshake() {
remove_action('login_head', 'wp_shake_js', 12);
}
add_action('login_head', 'wpb_remove_loginshake');
// Cleaner Filenames
function awp_sanitize_file_name( $filename ) {
$sanitized_filename = remove_accents( $filename ); // Convert to ASCII
$invalid = array(' ' => '-', '%20' => '-', '_' => '-');
$sanitized_filename = str_replace( array_keys( $invalid ), array_values( $invalid ), $sanitized_filename );
$sanitized_filename = preg_replace('/[^A-Za-z0-9-\. ]/', '', $sanitized_filename); // Remove all non-alphanumeric except .
$sanitized_filename = preg_replace('/\.(?=.*\.)/', '', $sanitized_filename); // Remove all but last .
$sanitized_filename = preg_replace('/-+/', '-', $sanitized_filename); // Replace any more than one - in a row
$sanitized_filename = str_replace('-.', '.', $sanitized_filename); // Remove last - if at the end
$sanitized_filename = strtolower( $sanitized_filename ); // Lowercase
return $sanitized_filename;
}
add_filter( 'sanitize_file_name', 'awp_sanitize_file_name', 10, 1 );
// Customize Login Panel
add_action( 'login_head', 'login_function' );
function login_function() {
add_filter( 'gettext', 'username_change', 20, 3 );
function username_change( $translated_text, $text, $domain ) {
if ( $text === 'Username or Email Address' ) {
$translated_text = 'Email';
}
return $translated_text;
}
}
// Custom Login Error Message
function change_wordpress_login_errors(){
return 'Salah euy, coba pariksa deui!';
}
add_filter( 'login_errors', 'change_wordpress_login_errors' );
// My Gravatar
function gravatawp_image($size = 16) {
$email_id = md5(strtolower(trim(get_bloginfo('admin_email'))));
return 'https://www.gravatar.com/avatar/' . $email_id . '?s=' . $size;
}
/* Gravatar as Favicon
function gravatawp_favicon() {
$email_id = md5(strtolower(trim(get_bloginfo('admin_email'))));
echo '<link rel="icon" href="'.gravatawp_image(32).'">';
}
add_action('wp_head', 'gravatawp_favicon');
add_action('admin_head', 'gravatawp_favicon');
add_action('login_head', 'gravatawp_favicon');
*/
/* Hide Author Box
function hide_author_bio() {
echo '<style>.post-author-bio {display: none !important;}</style>';
}
add_action('wp_head', 'hide_author_bio');
*/
// Set Default Avatar
function ec_custom_gravatar($default_gravatar) {
$logo = 'https://avatarys.com/var/resizes/Cool-Avatars/Twitter-Avatars/xCool,P20Twitter,P20Avatar,P20Default,P20avatar.png,qm=1435520538.pagespeed.ic.PPlcbOuD8e.webp';
$default_gravatar[$logo] = 'Avatar Gue';
return $default_gravatar;
}
add_filter( 'avatawp_defaults', 'ec_custom_gravatar' );
// Customize Login Page
function my_login_logo_url_title() { return 'Back to ' . get_bloginfo('name'); }
function my_login_logo_url() { return get_bloginfo('url'); }
function change_admin_login_logo() {
$css = '<style>#login h1 a, .login h1 a { background-image: url("'.gravatawp_image(100).'");';
$css .= 'width: 100px; height: 100px; background-size: cover; display: block; border: none;';
$css .= 'border-radius: 100px; -webkit-border-radius: 100px; -moz-border-radius: 100px; } p#nav {text-align: center; color: #fff;}';
//$css .= 'body.login { background-image: url("https://source.unsplash.com/random/1920x1200"); background-size: 100%; background-attachment: fixed;}';
$css .= '.forgetmenot, #backtoblog a:first-child{ display: none !important;} #wp-submit {width: 100%;}</style>';
echo $css;
}
add_action( 'login_enqueue_scripts', 'change_admin_login_logo' );
add_filter( 'login_headertitle', 'my_login_logo_url_title' );
add_filter( 'login_headerurl', 'my_login_logo_url' );
/* First Attached Image as Featured Image
function auto_featured_image() {
global $post;
if (!has_post_thumbnail($post->ID)) {
$attached_image = get_children( "post_parent=$post->ID&amp;post_type=attachment&amp;post_mime_type=image&amp;numberposts=1" );
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment_id);
}
}
}
}
function entry_thumbnail() {
echo '<style>div.entry-thumbnail img {width: 100% !important;}</style>';
}
add_action( 'wp_head', 'entry_thumbnail');
add_action('the_post', 'auto_featured_image');
add_action('save_post', 'auto_featured_image');
add_action('draft_to_publish', 'auto_featured_image');
add_action('new_to_publish', 'auto_featured_image');
add_action('pending_to_publish', 'auto_featured_image');
add_action('future_to_publish', 'auto_featured_image');
*/
// Change Howdy Label Admin Panel
add_action( 'admin_bawp_menu', 'wp_admin_bawp_my_custom_account_menu', 11 );
function wp_admin_bawp_my_custom_account_menu( $wp_admin_bar ) {
$user_id = get_current_user_id();
$current_user = wp_get_current_user();
$profile_url = get_edit_profile_url( $user_id );
if ( 0 != $user_id ) {
$avatar = get_avatar( $user_id, 28 );
$howdy = sprintf( __('Hola, %1$s'), $current_user->display_name );
$class = empty( $avatar ) ? '' : 'with-avatar';
$wp_admin_bar->add_menu(array(
'id' => 'my-account',
'parent' => 'top-secondary',
'title' => $howdy . $avatar,
'href' => $profile_url,
'meta' => array(
'class' => $class,
)));
}
}
// Remove Update Notice for Inacvite Plugins
function update_active_plugins($value = '') {
if ((isset($value->response)) && (count($value->response))) {
// Get the list cut current active plugins
$active_plugins = get_option('active_plugins');
if ($active_plugins) {
// Here we start to compare the $value->response
// items checking each against the active plugins list.
foreach($value->response as $plugin_idx => $plugin_item) {
// If the response item is not an active plugin then remove it.
// This will prevent WordPress from indicating the plugin needs update actions.
if (!in_array($plugin_idx, $active_plugins))
unset($value->response[$plugin_idx]);
}
} else {
// If no active plugins then ignore the inactive out of date ones.
foreach($value->response as $plugin_idx => $plugin_item) {
unset($value->response);
}
}
}
return $value;
}
add_filter('site_transient_update_plugins', 'update_active_plugins');
// Hide Admin Bar for spesific users
function df_disable_admin_bar() {
// we're getting current user ID
$user = get_current_user_id();
if ($user != 1) {
// for the admin page
remove_action('admin_footer', 'wp_admin_bawp_render', 1000);
// for the front-end
remove_action('wp_footer', 'wp_admin_bawp_render', 1000);
// css override for the admin page
function remove_admin_bawp_style_backend() {
echo '<style>body.admin-bar #wpcontent, body.admin-bar #adminmenu { padding-top: 0px !important; }</style>';
}
add_filter('admin_head','remove_admin_bawp_style_backend');
// css override for the frontend
function remove_admin_bawp_style_frontend() {
echo '<style>html { margin-top: 0px !important; } * html body { margin-top: 0px !important; }</style>';
}
add_filter('wp_head','remove_admin_bawp_style_frontend', 99);
}
}
add_action('init','df_disable_admin_bar');
// Add URL Column Media Library
function muc_column( $cols ) {
$cols["media_url"] = "URL";
return $cols;
}
function muc_value( $column_name, $id ) {
if ( $column_name == "media_url" ) echo '&nbsp;&nbsp;<input type="text" width="100%" onclick="jQuery(this).select();" value="'. wp_get_attachment_url( $id ). '" readonly="true">';
}
add_filter( 'manage_media_columns', 'muc_column' );
add_action( 'manage_media_custom_column', 'muc_value', 10, 2 );
// Ad Add Author Profile Fields
function wpb_new_contactmethods( $contactmethods ) {
$contactmethods['instagram'] = 'Instagram';
$contactmethods['twitter'] = 'Twitter';
$contactmethods['facebook'] = 'Facebook';
$contactmethods['github'] = 'Github';
return $contactmethods;
}
add_filter('user_contactmethods','wpb_new_contactmethods', 10, 1);
// Additional File Types to be Uploaded
function my_myme_types($mime_types){
$mime_types['svg'] = 'image/svg+xml';
$mime_types['psd'] = 'image/vnd.adobe.photoshop';
return $mime_types;
}
add_filter('upload_mimes', 'my_myme_types', 1, 1);
/***************************************************************
* Add Justify and Underline
***************************************************************/
add_filter( 'mce_buttons', 'awp_tiny_mce_buttons_rearrange', 5 );
add_filter( 'mce_buttons_2', 'awp_tiny_mce_buttons_2_rearrange', 5 );
function awp_tiny_mce_buttons_rearrange_list(){
return $mce_buttons = array(
'formatselect', // Dropdown list with block formats to apply to selection.
'bold', // Applies the bold format to the current selection.
'italic', // Applies the italic format to the current selection.
'underline', // Applies the underline format to the current selection.
'bullist', // Formats the current selection as a bullet list.
'numlist', // Formats the current selection as a numbered list.
'blockquote', // Applies block quote format to the current block level element.
'hr', // Inserts a horizontal rule into the editor.
'alignleft', // Left aligns the current block or image.
'aligncenter', // Left aligns the current block or image.
'alignright', // Right aligns the current block or image.
'alignjustify', // Full aligns the current block or image.
'link', // Creates/Edits links within the editor.
'unlink', // Removes links from the current selection.
'wp_more', // Inserts the <!-- more --> tag.
'spellchecker', // ???
'wp_adv', // Toggles the second toolbar on/off.
'dfw' // Distraction-free mode on/off.
);
}
function awp_tiny_mce_buttons_2( $buttons_array ){
$mce_buttons_2 = array(
'formatselect', // Dropdown list with block formats to apply to selection.
'underline', // Applies the underline format to the current selection.
'alignjustify', // Full aligns the current block or image.
'forecolor', // Applies foreground/text color to selection.
'pastetext', // Toggles plain text pasting mode on/off.
'removeformat', // Removes the formatting from the current selection.
'charmap', // Inserts custom characters into the editor.
'outdent', // Outdents the current list item or block element.
'indent', // Indents the current list item or block element.
'undo', // Undoes the last operation.
'redo', // Redoes the last undoed operation.
'wp_help' // Opens the help.
);
if ( in_array( 'code', $buttons_array ) ){ $mce_buttons_2[] = 'code'; }
return $mce_buttons_2;
}
function awp_tiny_mce_buttons_rearrange( $buttons_array ){
$mce_buttons = awp_tiny_mce_buttons_rearrange_list();
//Keep extra buttons by comparing two buttons lines
$mce_buttons_2 = awp_tiny_mce_buttons_2_rearrange_list();
foreach( $buttons_array as $button ){
if( !in_array( $button, $mce_buttons ) && !in_array( $button, $mce_buttons_2 ) ){
array_push( $mce_buttons, $button );
}
}
return $mce_buttons;
}
function awp_tiny_mce_buttons_2_rearrange( $buttons_array ){
$mce_buttons_2 = awp_tiny_mce_buttons_2_rearrange_list();
//Keep extra buttons by comparing two buttons lines
$mce_buttons = awp_tiny_mce_buttons_rearrange_list();
foreach( $buttons_array as $button ){
if( !in_array( $button, $mce_buttons_2 ) && !in_array( $button, $mce_buttons ) ){
array_push( $mce_buttons_2, $button );
}
}
return $mce_buttons_2;
}
function awp_tiny_mce_buttons_2_rearrange_list(){
return $mce_buttons_2 = array(
'strikethrough', // Applies strike though format to the current selection.
'forecolor', // Applies foreground/text color to selection.
'pastetext', // Toggles plain text pasting mode on/off.
'removeformat', // Removes the formatting from the current selection.
'charmap', // Inserts custom characters into the editor.
'outdent', // Outdents the current list item or block element.
'indent', // Indents the current list item or block element.
'undo', // Undoes the last operation.
'redo', // Redoes the last undoed operation.
'wp_help' // Opens the help.
);
}
/* Syntax HighlightJS
add_action( 'wp_enqueue_scripts', 'awp_highlightjs', 11 );
function awp_highlightjs() {
if(is_single() || is_page()) {
wp_enqueue_style( 'highlightjs', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/dracula.min.css', array(), '9.12.0', '');
wp_enqueue_script( 'highlightjs', 'https://pastebin.com/raw/4yhB4GFa', array(), '9.12.0', '');
}
}
function awp_highlightjs_init() {
if(is_single() || is_page()) {
echo "<script>hljs.initHighlightingOnLoad();</script>";
}
}
add_action( 'wp_footer', 'awp_highlightjs_init', 10 );
function awp_highlightjs_head() {
if(is_single() || is_page()) {
echo "<style>pre {margin:0; padding:0; display: flex; white-space: normal; word-break: break-word;} pre > code {margin: 0; padding: 15px 20px !important; display: block; width: 100%;}</style>";
}
}
add_action( 'wp_head', 'awp_highlightjs_head', 10 );
*/
/* Last Update Information in Single Page Footer
function awp_last_updated_date( $content ) {
if(is_single() || is_page()) {
$u_time = get_the_time('U');
$u_modified_time = get_the_modified_time('U');
$custom_content .= $content;
$can_edit = (is_user_logged_in()) ? '&nbsp;|&nbsp;<a href="'.get_bloginfo('url').'/wp-admin/post.php?post='.get_the_ID().'&action=edit">Edit</a>' : '';
if ($u_modified_time >= $u_time + 86400) {
$updated_date = get_the_modified_time('j F Y');
$updated_time = get_the_modified_time('H:i');
$custom_content .= '<hr/><p><small><em>Last updated on '. $updated_date . ' at '. $updated_time . $can_edit . '</em></small></p>';
}
return $custom_content;
} else {
return $content;
}
}
add_filter( 'the_content', 'awp_last_updated_date' );
*/
// Hide Title in Page
function hide_title_page() {
if (is_page()) {
echo "<style>.juicer-feed h1.referral {display: none !important;} .entry-title {display: none;}</style>";
}
}
add_filter('wp_head', 'hide_title_page');
// Hide WP Logo Admin Panel
function annointed_admin_bar_remove() {
global $wp_admin_bar;
$wp_admin_bar->remove_menu('wp-logo');
$wp_admin_bar->remove_menu('view-site');
}
add_action('wp_before_admin_bar_render', 'annointed_admin_bar_remove', 0);
// Remove Standar Widget
function unregister_default_wp_widgets() {
unregister_widget('WP_Widget_Calendar');
unregister_widget('WP_Widget_Calendar');
unregister_widget('WP_Widget_Recent_Comments');
}
add_action('widgets_init', 'unregister_default_wp_widgets', 1);
// Remove MetaBoxes
function remove_meta_boxes() {
# Removes meta from Posts #
remove_meta_box('postcustom','post','normal');
remove_meta_box('trackbacksdiv','post','normal');
remove_meta_box('commentstatusdiv','post','normal');
remove_meta_box('commentsdiv','post','normal');
# Removes meta from pages #
remove_meta_box('postcustom','page','normal');
remove_meta_box('trackbacksdiv','page','normal');
remove_meta_box('commentstatusdiv','page','normal');
remove_meta_box('commentsdiv','page','normal');
}
add_action('admin_init','remove_meta_boxes');
// Load jQuery in Footer
function jquery_in_footer( &$scripts) {
if ( ! is_admin() )
$scripts->add_data( 'jquery', 'group', 1 );
}
add_action( 'wp_default_scripts', 'jquery_in_footer' );
// Remove SubMenu Admin Panel
function remove_submenus() {
global $submenu;
unset($submenu['index.php'][10]);
unset($submenu['plugins.php'][10]);
unset($submenu['plugins.php'][15]);
unset($submenu['upload.php'][5]);
unset($submenu['upload.php'][10]);
unset($submenu['tools.php'][5]);
unset($submenu['users.php'][5]);
unset($submenu['users.php'][10]);
unset($submenu['users.php'][15]);
//unset($submenu['options-general.php'][25]);
}
add_action('admin_menu', 'remove_submenus');
// Hiding Password Protected Posts in WordPress
add_action( 'pre_get_posts', 'prefix_exclude_password_protected_posts' );
function prefix_exclude_password_protected_posts( $query ) {
if ( ! $query->is_singular() && ! is_admin() ) {
$query->set( 'has_password', false );
}
}
// Hide Personal Options
function hide_personal_options(){
echo "\n" . '<script type="text/javascript">jQuery(document).ready(function($) { $(\'form#your-profile > h2:first\').hide(); $(\'form#your-profile > h3:first\').hide(); $(\'form#your-profile > table:first\').hide(); $(\'form#your-profile\').show(); });</script>' . "\n";
}
add_action('admin_head','hide_personal_options');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment