This is my collection of WordPress, CSS, JS and PHP code

July 1, 2014 (6 years ago)
General

This is a personal collection of snippets I use on client sites. Some are original, some highly modified or cobbled together from other sources, and some copied (only from open sources such as this.)

I generally prefer not to use plugins for simple features and functions, especially if my clients don’t need options, which is quite often the case.

Free support for these snippets is probably not an option for your unique applications, due to my work load, but it never hurts to ask.

Copy, share and code on!

Super Simple Floating Button

December 4, 2018 (2 years ago)
General

Forget complicated plugins with tons of options you don’t need.
Easily create a floating button on your site with this simple CSS:

.button.float{
    position:fixed !important;
    bottom:20px;
    right:20px;
    z-index:999999;
}

Then just add this anywhere on your page or template:

<div class="button float">
     <a href="#">Click Me</a>
</div>

In this example, I used the class ‘button’ because the styling for that is already in my theme. You can remove that class and add the styles in the CSS above if you like.

WordPress ScrollTo Hash

October 31, 2017 (3 years ago)
WordPress, JS

I needed to pass a hash, and scroll to the matching anchor on a new page.

Not as easy as it sounds in WordPress. (Pretty permalinks make it not work.)

After much testing and research, here’s the solution that worked best:

<script>
jQuery( document ).ready(function($) {
   var thehash = window.location.hash.replace('#', '');
   $('body, html').animate({ scrollTop: $('.'+thehash).offset().top -150 }, 1000);
});
</script>

I added the “-150” after the offset to show the header above the anchor.

WooCommerce – Conditional Ship to a Different Address Selection

October 31, 2017 (3 years ago)
WooCommerce, WordPress, JS, Functions

The scenario is this:

The site has multiple shipping methods (multiple client locations, and the option to ship to “Other”.)

I wanted to show the address panel if “Other” location was chosen, and hide the “Ship to Another Location”  option heading on the shipping page if a client location was chosen.

None of this was strictly necessary, but it makes for a smoother customer experience.

This went into my functions.php file.

/* added with my other enqueued scripts */
   wp_register_script( 'hideshipto', get_bloginfo( 'stylesheet_directory' ) . '/hide_ship_to.js', array( 'jquery' ) );


add_action( 'init', 'fb_ship_to_open' ); // opens the ship to for church dlievery or hides the ship to a different address for all others
function fb_ship_to_open () {
  global $woocommerce;
    if ( !is_admin() && WC()->session->get( 'chosen_shipping_methods' ) ) {
    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0]; 
      if ('your_shipping_method_goes_here' == $chosen_shipping ) {
        add_filter( 'woocommerce_ship_to_different_address_checked', '__return_true' );
      } else {
        add_action( 'wp_enqueue_scripts', 'fb_load_ship_script' );
          function fb_load_ship_script() {
        wp_enqueue_script( 'hideshipto');
        }
      }
    }
  }

Then, this is the hide_ship_to.js script file. (uploaded to the theme directory)

jQuery( document ).ready(function($) {
    $('#ship-to-different-address').hide();
});

 

Adding FontAwesome Icon to CSS

October 20, 2017 (3 years ago)
CSS

To add an icon using only CSS (for example, before list items), use this code:

&:before { font: normal normal normal 14px/1 FontAwesome; content: '\f0a9'; margin-right:10px;

Of course, you’ll need to have the FontAwesome font installed on your site.

Get the unicodes for icons here:  http://fontawesome.io/cheatsheet/

A Simple jQuery Accordion

February 27, 2017 (3 years ago)
JS, Functions

No need for the overhead of a plugin.

In this case, I have a custom post type for FAQs, where the title is the question, and the content is the answer.

This script hides all the answers until one of the questions is clicked.

Here’s the JavaScript:

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $('.accordion').on('click', function() {
            $parent_box = $(this).closest('.faqbox');
            $parent_box.siblings().find('.panel').hide();
            $parent_box.find('.panel').toggle();
        });
    });
</script>

And the HTML:

<?php while ( have_posts() ) : the_post(); ?>

     <div class="faqbox">
          <h4 class="accordion"><i class="fa fa-plus-square" aria-hidden="true"></i> <?php the_title(); ?></h4>
          <div class="panel"><?php the_content(); ?></div>
     </div>

<?php    endwhile; ?>

 

Then, this little bit of CSS brings it together:

.faqbox { margin: 1em 0 0;
  .panel { display: none;  margin-left: 1em; }
  .accordion { cursor:pointer; }
}

 

Change the Text of Reset Password Email

September 25, 2016 (4 years ago)
WordPress, PHP, Functions

Send a custom message to users who request a password re-set:

//* Password reset activation E-mail -> Body
add_filter( 'retrieve_password_message', 'dnlt_retrieve_password_message', 10, 2 );

function dnlt_retrieve_password_message( $message, $key ){
    $user_data = '';
    // If no value is posted, return false
    if( ! isset( $_POST['user_login'] )  ){
            return '';
    }
    // Fetch user information from user_login
    if ( strpos( $_POST['user_login'], '@' ) ) {

        $user_data = get_user_by( 'email', trim( $_POST['user_login'] ) );
    } else {
        $login = trim($_POST['user_login']);
        $user_data = get_user_by('login', $login);
    }
    if( ! $user_data  ){
        return '';
    }
    $user_login = $user_data->user_login;
    $user_email = $user_data->user_email;
    // Setting up message for retrieve password
    $message = "A password reset has been requested for this site:\n\n";
    $message .= network_home_url( '/' ) . "\r\n\r\n";
    $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";  
    $message .= "Change this text to whatever you like.\n\n";
    $message .= "If you did not request this, just ignore this email and nothing will happen.\n\n"; 
    $message .= "To reset your password, visit the following address:\n";
    $message .= network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login');
    
    return $message;
}

 

Remove WP Version Number

September 23, 2016 (4 years ago)
WordPress, Best Practices, Functions

Prevent robot scrapers from easily finding out which version of WordPress you’re running.

Not a substitute for keeping WP updated, but a handy fallback for clients who may not.

/* remove WP version number */
if ( ! function_exists( 'dnlt_remove_wp_version' ) ) {
    add_filter( 'the_generator', 'dnlt_remove_wp_version' );

    function dnlt_remove_wp_version() {
        return '';
    }
}

 

List all Posts

August 4, 2016 (4 years ago)
WordPress

Outputs a single list of all your posts.

include "wp-load.php";

$posts = new WP_Query('post_type=post&posts_per_page=-1&post_status=publish');
$posts = $posts->posts;

foreach($posts as $post) {    
     $permalink = get_permalink($post->ID);
     echo "{$post->post_date} -- <a href='{$permalink}'>{$permalink}</a><br />";
}

Thanks, Mickey! (Edited a bit for simplicity)

Create Admin User via FTP

July 9, 2016 (4 years ago)
Functions

When you are locked out of your WordPress site and have no access to PHPMyAdmin, add this to your functions.php file to create a new admin user account.

Remove it from the functions file after you’re successfully logged in. (The user will remain.)

function wpb_admin_account(){
   $user = 'Username';
   $pass = 'Password';
   $email = 'email@domain.com';
   if ( !username_exists( $user )  && !email_exists( $email ) ) {
      $user_id = wp_create_user( $user, $pass, $email );
      $user = new WP_User( $user_id );
      $user->set_role( 'administrator' );
} }
add_action('init','wpb_admin_account');

Thanks for the snippet, WPBeginner!

Adding Content to the Admin Edit Screen

October 30, 2015 (5 years ago)
WordPress, Functions

When creating custom post types, you often need custom fields for them. In the past, your options were “normal” or “side” with priorities. Depending on what else is displayed on your edit screen, these boxes could vary in where they appeared.

And sometimes you just need to add a comment or note to the edit pages.

Good News! We now have new hooks to place them precisely:

add_action( 'edit_form_top', 'myprefix_edit_form_top' );
function myprefix_edit_form_top() {
    echo '<h2>This is edit_form_top!</h2>';
}

add_action( 'edit_form_after_title', 'myprefix_edit_form_after_title' );
function myprefix_edit_form_after_title() {
    echo '<h2>This is edit_form_after_title!</h2>';
}
 
add_action( 'edit_form_after_editor', 'myprefix_edit_form_after_editor' );
function myprefix_edit_form_after_editor() {
    echo '<h2>This is edit_form_after_editor!</h2>';
}
 
add_action( 'edit_form_advanced', 'myprefix_edit_form_advanced' );
function myprefix_edit_form_advanced() {
    echo '<h2>This is ye olde edit_form_advanced!</h2>';
}

Here’s an article that explains the usage: https://make.wordpress.org/core/2012/12/01/more-hooks-on-the-edit-screen/

 

Next »

Skip to toolbar