Skip to content

Instantly share code, notes, and snippets.

@JTruax
Last active June 29, 2023 17:54
Show Gist options
  • Save JTruax/ba10009230a925335a59b7a83ed3df42 to your computer and use it in GitHub Desktop.
Save JTruax/ba10009230a925335a59b7a83ed3df42 to your computer and use it in GitHub Desktop.
WordPress Function Snippets
<!--------------------------------------------------------
SNIPPETS INDEX
-- 01 - Enqueue Google Fonts
-- 02 - Make jQuery load from Google Library
-- 03 - Customize excerpt length and read more characters
-- 04 - Enable Pagination Links
-- 05 - Replace WP login logo with custom
-- 06 - Displays a custom Dashboard Widget
-- 07 - Allow different file formats in Media Library
-- 08 - Turn Off Your Self-referring Pingbacks
-- 09 - Inject Post Images Into the RSS Feed
-- 10 - Responsive Videos – YouTube and Vimeo
-- 11 - Custom Sidebars
-- 12 - Modifies tag cloud widget arguments to have all tags in the widget same font size
-- 13 - Expanding Your User Profile With Further Social Media Accounts
-- 14 - Make Post Images Mandatory
-- 15 - Change the Look of the First Paragraph
-- 16 - Load the Entire JavaScript in the Footer
-- 17 - Create a Breadcrumb Navigation Without a Plugin
-- 18 - Related posts
-- 19 - Hide Plugin
-- 20 - Hide Username
-- 21 - Limit Login Attempts
<!--------------------------------------------------------
-- 01 - Enqueue Google Fonts
--------------------------------------------------------->
<?php
function google_fonts() {
wp_register_style('OpenSans', 'https://fonts.googleapis.com/css?family=Open+Sans:400,400i,600i,700,700i,800');
wp_enqueue_style( 'OpenSans');
}
add_action( 'wp_print_styles', 'google_fonts' );
?>
<!--------------------------------------------------------
-- 02 - Make jQuery load from Google Library
--------------------------------------------------------->
<?php
function replace_jquery() {
if (!is_admin()) {
wp_deregister_script('jquery');
wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', false, '1.11.0');
wp_enqueue_script('jquery');
}
}
add_action('init', 'replace_jquery');
?>
<!--------------------------------------------------------
-- 03 - Customize excerpt length and read more characters
--------------------------------------------------------->
<?php
function wpt_excerpt_length( $length ) {
return 50;
}
add_filter( 'excerpt_length', 'wpt_excerpt_length', 999 );
//Custom Read More Excerpt
function new_excerpt_more( $more ) {
return '...';
}
add_filter('excerpt_more', 'new_excerpt_more');
?>
<!----- USE WITH ----->
// Deleting the original tag:
<?php the_excerpt(); ?>
// Exchange with this tag, and enter any length (in brackets):
<?php the_excerpt_max_charlength( 250 ); ?>
<!--------------------------------------------------------
-- 04 - Enable Pagination Links
--------------------------------------------------------->
<?php
if ( ! function_exists( 'my_pagination' ) ) :
function my_pagination() {
global $wp_query;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages,
'prev_text' => 'Newer Posts',
'next_text' => 'Older Posts'
) );
}
endif;
?>
<!----- USE WITH ----->
<?php my_pagination(); ?>
<!--------------------------------------------------------
-- 05 - Replace WP login logo with custom
--------------------------------------------------------->
<?php
function my_login_logo() { ?>
<style type="text/css">
#login h1 a, .login h1 a {
background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/images/LOGO.png);
background-size: 260px 110px;
width: 260px;
height: 110px;
}
</style>
<?php }
add_action( 'login_enqueue_scripts', 'my_login_logo' );
?>
<!--------------------------------------------------------
-- 06 - Displays a custom Dashboard Widget
--------------------------------------------------------->
<?php
function ah_custom_dashboard_widgets() {
global $wp_meta_boxes;
wp_add_dashboard_widget('custom_help_widget', 'Theme Support', 'ah_custom_dashboard_help');
}
function ah_custom_dashboard_help() {
echo '<p>Custom dashboard widget via functions.php</p>';
}
add_action('wp_dashboard_setup', 'ah_custom_dashboard_widgets');
?>
<!--------------------------------------------------------
-- 07 - Allow different file formats in Media Library
--------------------------------------------------------->
<?php
/**
* Add further Mime types for the download of the products
*/
function add_custom_mime_types($mimes){
$new_file_types = array (
'zip' => 'application/zip',
'mobi' => 'application/x-mobipocket-ebook',
'pdf' => 'application/pdf',
'epub' => 'application/epub+zip'
);
return array_merge($mimes,$new_file_types);
}
add_filter('upload_mimes','add_custom_mime_types');
?>
<!--------------------------------------------------------
-- 08 - Turn Off Your Self-referring Pingbacks
--------------------------------------------------------->
<?php
function evolution_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', 'evolution_no_self_ping' );
?>
<!--------------------------------------------------------
-- 09 - Inject Post Images Into the RSS Feed
--------------------------------------------------------->
<?php
/**
* Add Post Images to the RSS Feed
*/
function evolution_featuredtoRSS($content) {
global $post;
if ( has_post_thumbnail( $post->ID ) ){
$content = '<div>' . get_the_post_thumbnail( $post->ID, 'large', array( 'style' => 'margin-bottom: 15px;' ) ) . '</div>' . $content;
}
return $content;
}
add_filter('the_excerpt_rss', 'evolution_featuredtoRSS');
add_filter('the_content_feed', 'evolution_featuredtoRSS');
?>
<!--------------------------------------------------------
-- 10 - Responsive Videos – YouTube and Vimeo
--------------------------------------------------------->
<?php
function evolution_wrap_oembed( $html ){
$html = preg_replace( '/(width|height)="\d*"\s/', "", $html ); // Strip width and height #1
return'<div class="embed-responsive embed-responsive-16by9">'.$html.'</div>'; // Wrap in div element and return #3 and #4
}
add_filter( 'embed_oembed_html','evolution_wrap_oembed',10,1);
?>
<!----- ADD TO CSS ----->
.embed-responsive.embed-responsive-16by9 {
position: relative;
padding-bottom: 56.25%; /* 16:9 */
padding-top: 25px;
height: 0;
}
.embed-responsive.embed-responsive-16by9 iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
/* This indication makes HTML5 videos responsive */
video {
width: 100% !important;
height: auto !important;
}
<!------------------------------------------------------------------
-- 11 - Custom Sidebars
------------------------------------------------------------------->
<?php if ( ! is_active_sidebar( 'sidebar-1' ) ) {
return;
}
?>
<?php
function humescores_widgets_init() {
//copy from HERE
register_sidebar( array(
'name' => esc_html__( 'Sidebar', 'humescores' ),
'id' => 'sidebar-1',
'description' => esc_html__( 'Add widgets here.', 'humescores' ),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
) );
//to HERE
}
add_action( 'widgets_init', 'humescores_widgets_init' );
?>
<!-----USE WITH----->
<?php dynamic_sidebar( 'sidebar-1' ); ?>
<!----------------------------------------------------------------------------------------
-- 12 - Modifies tag cloud widget arguments to have all tags in the widget same font size
----------------------------------------------------------------------------------------->
<?php
function blog_widget_tag_cloud_args( $args ) {
$args['largest'] = 1;
$args['smallest'] = 1;
$args['unit'] = 'em';
return $args;
}
add_filter( 'widget_tag_cloud_args', 'blog_widget_tag_cloud_args' );
?>
<!----------------------------------------------------------------------
-- 13 - Expanding Your User Profile With Further Social Media Accounts
----------------------------------------------------------------------->
<?php
/**
* Managing contact fields for author bio
*/
$evolution_pro_Contactfields = new evolution_pro_Contactfields(
// Missing accounts can easily be added
array (
'Feed',
'Twitter',
'Facebook',
'GooglePlus',
'Flickr',
'Xing',
'Github',
'Instagram',
'LinkedIn',
'Pinterest',
'Vimeo',
'Youtube'
)
);
class evolution_pro_Contactfields {
public
$new_fields
, $active_fields
, $replace
;
/**
* @param array $fields New fields: array ('Twitter', 'Facebook')
* @param bool $replace Replace default fields?
*/
public function __construct($fields, $replace = TRUE)
{
foreach ( $fields as $field )
{
$this->new_fields[ mb_strtolower($field, 'utf-8') ] = $field;
}
$this->replace = (bool) $replace;
add_filter('user_contactmethods', array( $this, 'add_fields' ) );
}
/**
* Changing contact fields
* @param $original_fields Original WP fields
* @return array
*/
public function add_fields($original_fields)
{
if ( $this->replace )
{
$this->active_fields = $this->new_fields;
return $this->new_fields;
}
$this->active_fields = array_merge($original_fields, $this->new_fields);
return $this->active_fields;
}
/**
* Helper function
* @return array The currently active fields.
*/
public function get_active_fields()
{
return $this->active_fields;
}
}
?>
<!----- USE WITH ----->
<?php
$twitter = get_the_author_meta( 'twitter', $post->post_author );
$facebook = get_the_author_meta( 'facebook', $post->post_author );
echo '<a href="https://twitter.com/' . $twitter .'" rel="nofollow" target="_blank">Twitter</a> | <a href="'. $facebook .'" rel="nofollow" target="_blank">Facebook</a>';
?>
<!--------------------------------------------------------
-- 14 - Make Post Images Mandatory
--------------------------------------------------------->
<?php
add_action('save_post', 'evolution_check_thumbnail');
add_action('admin_notices', 'evolution_thumbnail_error');
function evolution_check_thumbnail($post_id) {
// change to any custom post type
if(get_post_type($post_id) != 'post')
return;
if ( !has_post_thumbnail( $post_id ) ) {
// set a transient to show the users an admin message
set_transient( "has_post_thumbnail", "no" );
// unhook this function so it doesn't loop infinitely
remove_action('save_post', 'evolution_check_thumbnail');
// update the post set it to draft
wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
add_action('save_post', 'evolution_check_thumbnail');
} else {
delete_transient( "has_post_thumbnail" );
}
}
function evolution_thumbnail_error()
{
// check if the transient is set, and display the error message
if ( get_transient( "has_post_thumbnail" ) == "no" ) {
echo "<div id='message' class='error'><p><strong>You have to assign a post image. Without a post image, the article can't be published.</strong></p></div>";
delete_transient( "has_post_thumbnail" );
}
}
?>
<!--------------------------------------------------------
-- 15 - Change the Look of the First Paragraph
--------------------------------------------------------->
<?php
/**
* Auto-Highlighting - Automatic highlighting of a post's first paragraph
* @author Andreas Hecht
*/
function tb_first_paragraph_highlight( $content ) {
return preg_replace( '/<p([^>]+)?>/', '<p$1 class="opener">', $content, 1 );
}
add_filter( 'the_content', 'tb_first_paragraph_highlight' );
?>
<!--------------------------------------------------------
-- 16 - Load the Entire JavaScript in the Footer
--------------------------------------------------------->
<?php
/**
* @uses wp_head() and wp_enqueue_scripts()
*
*/
if ( !function_exists( 'evolution_footer_scripts' ) ) {
function evolution_footer_scripts() {
remove_action('wp_head', 'wp_print_scripts');
remove_action('wp_head', 'wp_print_head_scripts', 9);
remove_action('wp_head', 'wp_enqueue_scripts', 1);
}
}
add_action( 'wp_enqueue_scripts', 'evolution_footer_scripts' );
?>
<!--------------------------------------------------------
-- 17 - Create a Breadcrumb Navigation Without a Plugin
--------------------------------------------------------->
<?php
// Copy from here
function ah_the_breadcrumb() {
echo '<ul id="crumbs">';
if (!is_home()) {
echo '<li><a href="';
echo get_option('home');
echo '">';
echo 'Home';
echo "</a></li>";
if (is_category() || is_single()) {
echo '<li>';
the_category(' </li><li> ');
if (is_single()) {
echo "</li><li>";
the_title();
echo '</li>';
}
} elseif (is_page()) {
echo '<li>';
echo the_title();
echo '</li>';
}
}
elseif (is_tag()) {single_tag_title();}
elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';}
elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';}
elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';}
elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';}
elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';}
elseif (is_search()) {echo"<li>Search Results"; echo'</li>';}
echo '</ul>';
}
?>
<!----- USE WITH ----->
<?php ah_the_breadcrumb(); ?>
<!-------------------------------------------------------------
-- 18 - Related posts filtered by Category, Use in Single.php
-------------------------------------------------------------->
<?php $orig_post = $post;
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=> 3, // Number of related posts that will be shown.
'caller_get_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
while( $my_query->have_posts() ) {
$my_query->the_post();?>
<div class="col-custom-related">
<a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>">
<?php the_post_thumbnail('large'); ?>
</a>
<p>
<a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>">
<?php the_title(); ?>
</a>
</p>
</div>
<?
}
}
}
$post = $orig_post;
wp_reset_query(); ?>
<!-------------------------------------------------------------------------------------------------------
-- 19 - Hide Plugin from dashboard. Place in functions.php, replace path from edit plugins pathname.
-------------------------------------------------------------------------------------------------------->
<?php
function hide_plugin_trickspanda() {
global $wp_list_table;
$hidearr = array('really-simple-ssl/rlrsssl-really-simple-ssl.php');
$myplugins = $wp_list_table->items;
foreach ($myplugins as $key => $val) {
if (in_array($key,$hidearr)) {
unset($wp_list_table->items[$key]);
}
}
}
add_action('pre_current_active_plugins', 'hide_plugin_trickspanda');
?>
<!-------------------------------------------------------------------------------------------------------
-- 20 - Hide Username & Administrator count. Place in functions.php
-------------------------------------------------------------------------------------------------------->
function hide_user_count(){
?>
<style>
table.wp-list-table tr#user-9, .subsubsub li.administrator span.count{display: none;}
</style>
<?php
}
<!-------------------------------------------------------------------------------------------------------
-- 21 - Limit Login Attempts
-------------------------------------------------------------------------------------------------------->
function check_attempted_login( $user, $username, $password ) {
if ( get_transient( 'attempted_login' ) ) {
$datas = get_transient( 'attempted_login' );
if ( $datas['tried'] >= 3 ) {
$until = get_option( '_transient_timeout_' . 'attempted_login' );
$time = time_to_go( $until );
return new WP_Error( 'too_many_tried', sprintf( __( '<strong>ERROR</strong>: You have reached authentication limit, you will be able to try again in %1$s.' ) , $time ) );
}
}
return $user;
}
add_filter( 'authenticate', 'check_attempted_login', 30, 3 );
function login_failed( $username ) {
if ( get_transient( 'attempted_login' ) ) {
$datas = get_transient( 'attempted_login' );
$datas['tried']++;
if ( $datas['tried'] <= 3 )
set_transient( 'attempted_login', $datas , 300 );
} else {
$datas = array(
'tried' => 1
);
set_transient( 'attempted_login', $datas , 300 );
}
}
add_action( 'wp_login_failed', 'login_failed', 10, 1 );
function time_to_go($timestamp)
{
// converting the mysql timestamp to php time
$periods = array(
"second",
"minute",
"hour",
"day",
"week",
"month",
"year"
);
$lengths = array(
"60",
"60",
"24",
"7",
"4.35",
"12"
);
$current_timestamp = time();
$difference = abs($current_timestamp - $timestamp);
for ($i = 0; $difference >= $lengths[$i] && $i < count($lengths) - 1; $i ++) {
$difference /= $lengths[$i];
}
$difference = round($difference);
if (isset($difference)) {
if ($difference != 1)
$periods[$i] .= "s";
$output = "$difference $periods[$i]";
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment