The following are various code snippets I picked up over the years for WordPress, jQuery, HTML, CSS, and htaccess. Instead of digging into my project files to reuse them during development, I decided it would be best to put them all here.

Advanced Custom Fields

Escape Fields in ACF

Updated: 05/13/2016 | View post

Sometimes you want to prevent users, either on the backend or frontend from inputting JS, HTML and other things that may cause problems into you custom fields. This function prevents that:

 
function get_sub_field_escaped($field_key, $post_id = false, $format_value = true, $escape_method = 'esc_html')
 {
 $field = get_sub_field($field_key, $post_id, $format_value);
 
 /* Check for null and falsy values and always return space */
 if($field === NULL || $field === FALSE)
 $field = '';
 
 /* Handle arrays */
 if(is_array($field))
 {
 $field_escaped = array();
 foreach($field as $key => $value)
 {
 $field_escaped[$key] = ($escape_method === NULL) ? $value : $escape_method($value);
 }
 return $field_escaped;
 }
 else
 return ($escape_method === NULL) ? $field : $escape_method($field);
 }

Then use this for fields you wanted escaped like so:

the_field_escaped('description');
get_field_escaped('description');
get_sub_field_escaped('description');

See the reference here

Create an Options Page (ACF 5+)

Updated: 05/13/2016 | View post

To create an options page in WordPress using Advanced Custom Fields use this code and alter the highlighted as needed:

add_action( 'admin_menu', 'add_new_page', 98 );

function add_new_page() { 
   if( function_exists('acf_add_options_page') ) {
       acf_add_options_page(array(
         'page_title' => 'Page Title',
         'menu_title' => 'Menu Title',
         'menu_slug' =>  'page-slug',
         'capability' => 'edit_posts',
         'redirect' => false
         )); 
    }
}

ACF repeater field code

Updated: 05/13/2016 | View post

Here’s the Advanced Custom Field code for a repeater field:

<?php if( have_rows('slider') ): ?>
   <?php // stuff before repeater ?>
   <ul>
   <?php while( have_rows('slider') ): the_row();?> 
   <?php // vars
      $link = get_sub_field('link');
   ?>

   <?php // stuff to be repeated ?>
    <li href="<?php echo $link; ?>"></li>

   <?php endwhile; ?>
   <?php // stuff after repeater ?>
   </ul>
<?php endif; ?>

CSS

CSS Content Counter with Decimal Leading Zero

Updated: 11/02/2016 | View post

.numbering { counter-reset:section }
.numbering h2:before { 
     counter-increment:section; 
     content:counter(section, decimal-leading-zero) ". ";
}

HTML looks like this:

<div class="numbering">
   <h2>Headline 1</h2>
...
   <h2>Heading 2</h2>
...
</div>

 

Disable Anchor Link with CSS

Updated: 09/03/2016 | View post

I never new this simple property. I was actually using JS to do disable links. But this is so simple.

.home > a { 
   pointer-events: none; cursor: default; 
}

Javascript / jQuery

Do something if the hashtag includes this word

Updated: 09/30/2016 | View post

This is short snippet that checks whether or not the URL has an appended hashtag and then does something. In this example #comment-123 and 123 being a variable is what I’m checking for.

Why I needed this?

On a blog of mind, I hide the comment section behind a short guidelines message. Users can’t see comments until they click a button to view and/or make a comment. Hidden comment section also shortens page space if someone is just skimming over the page.

This worked find if a person landed on the page normally, but what if they landed on the page via a direct comment link like this http://website.com/post-name/#comment-456 ? They’d be taken to that part of the comment, but find the comment section hidden. Then they’d have to click to read the comments, but clicking would only display the comments starting from the top. This isn’t helpful.

This script will automatically open the comment section only for people visiting the page with a direct comment link and take them directly to the comment.

Feel free to change the highlighted to whatever name is your hashtag starts with. The script will handle the rest.

if (window.location.hash) {
   if (window.location.hash.indexOf('comment-') == 1) { // your code here }
   else if (window.location.hash.indexOf('comment-') != -1) { // your code here }
   else { }
}

Source

Add a class to the currently clicked element in a parent

Updated: 05/13/2016 | View post

The following code will add a class called active to the list element that is currently clicked.

jQuery(function () {
    jQuery(".remove-bullets li").click(function (e) {
       e.preventDefault();
       jQuery(".remove-bullets li").addClass("active").not(this).removeClass("active");
    });
});

The HTML

<ul class="remove-bullets">
   <li>...</li>
   <li>...</li>
</ul>

On the click of one of the list elements, a class would be added like so:

<ul class="remove-bullets">
   <li>...</li>
   <li class="active">...</li>
</ul>

Copy and/or move element(s) and display elsewhere

Updated: 05/13/2016 | View post

In the below script, the element #shopping-cart is copied (cloned) and then appended to the element #menu-button.

jQuery(document).ready(function() {
    jQuery( "#shopping-cart" ).clone().append( "#menu-button" );
});

In the below script, the element #shopping-cart is moved from it’s original place in the markup to after #menu-button.

jQuery(document).ready(function() {
    jQuery( "#shopping-cart" ).after( "#menu-button" );
});

Here’s a guide to the right methods to use:

  • append = add the element inside just before the closing tag
  • prepend = add the element inside just after the opening tag
  • before = add the element before another element
  • after = add the element after another element

Truncate and toggle list elements using jQuery

Updated: 05/13/2016 | View post

The jQuery:

// Details: http://jsfiddle.net/ztKUX/2/
$(document).ready(function(){
 
 $('.ShowHideFullLists').click (ShowHideFullLists);
 $('.ShowHideFullLists').click (); //-- Init list displays.
 
 function ShowHideFullLists () {
 var showHideBtn = $(this);
 var bShowEm = showHideBtn.data ('bShowEm') || false;
 
 // Find the list for this button. It is a previous sibling, in the HTML.
 var thisBtnsList = showHideBtn.prev ("ul.truncate-list");
 
 // Show either all or the # from the data-list-items attribute.
 ShowItems (thisBtnsList, bShowEm, thisBtnsList.data ('listItems') );
 
 // Update the show-all flag.
 bShowEm ^= true;
 showHideBtn.data ('bShowEm', bShowEm);
 
 // Update the button text.
 if (bShowEm)
 showHideBtn.text ('Show More');
 else
 showHideBtn.text ('Show Less');
 }
 
 function ShowItems (parentNode, bShowAll, numVisible) {
 
 if (bShowAll)
 parentNode.find ("> li").show ();
 else {
 parentNode.find ("> li:lt(" + numVisible + ")").show ();
 parentNode.find ("> li:gt(" + (numVisible-1) + ")").hide ();
 }
 }
 
});

The HTML

<ul class="truncate-list" data-list-items="3"> 
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
<button class="ShowHideFullLists" type="button">View All</button>

Disable an anchor link using jQuery

Updated: 05/13/2016 | View post

jQuery('.anchorlink').on('click', function(e) { e.preventDefault(); });

Conditional jQuery based off of media queries

Updated: 05/13/2016 | View post

The highlighted media queries are what the script will look for to load any additional jQuery scripts and commands. Change these lines to whatever you’d like. Then place whatever script that will be executed inside.

jQuery(document).ready(function() {
   checkSize(); jQuery(window).resize(checkSize); function checkSize(){
      if (jQuery('.header-two').css('display') == 'block'){
          // jQuery rules here
      }
      if (jQuery('.header-two').css('display') == 'none'){
         // JQuery rules here
      }
   };   
});

 

PHP

Increase the file upload size limit in WordPress

Updated: 10/30/2016 | View post

Find the php.ini file on your server and the lines below (change the number to something higher):

post_max_size = 8M
upload_max_filesize = 2M

Increase the timeout time in WordPress

Updated: 10/30/2016 | View post

Sometimes scripts take to long to work and they time out, leaving you with an error. While this is a bandage to the situation, it still work. Add this to your .htaccess file:

php_value max_execution_time 600

Uncategorized

.htaccess file bits

Updated: 05/13/2016 | View post

Here’s a few codes I’ve picked up over the years for the powerful .htaccess file. These work only for Apache Linux servers:

Redirection:

If you want to redirect all pages of an entire site to the main page of another domain, add the following code to the file, on a single line.

RedirectMatch 301 (.*) http://www.yournewdomain.com/

If you want to redirect one page to another page, add the following code to the file, on a single line.

redirect 301 /old-file-name.htm http://new-websites.com/new-file-name.htm

If you want to redirect all non-www requests to your site to the www version, all you need to do is add the following:

RewriteEngine On 
RewriteCond %{HTTP_HOST} !^www. 
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Do it in reverse:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^my-domain.com$ [NC]
RewriteRule ^(.*)$ http://my-domain.com/$1 [R=301,L]

Make sure to replace “my-domain” and other sample addresses with your own.


Make sure the character set is explicit on the server

utf-8 is the standard and most used:

AddDefaultCharset utf-8 
AddCharset utf-8 .html .css .js .xml .json .rss .atom

Make sure audio/video works by defining the MIME type on the server:

AddType video/ogg .ogv
AddType video/mp4 .mp4
AddType video/webm .webm

More here: http://perishablepress.com/stupid-htaccess-tricks/#redirects

WordPress

Add post formats to Custom Post Types

Updated: 07/05/2017 | View post

Add this to your functions.php file. Make sure your change the prefix name to your own.

// add post-formats to post_type 'my_custom_post_type'

function prefix_custom_post_formats_setup() {
   add_post_type_support( 'my_custom_post_type', 'post-formats' );
}
add_action( 'init', 'prefix_custom_post_formats_setup' );

Make WordPress generate additional custom-sized images

Updated: 12/25/2016 | View post

Add this to your function.php file and change the highlighted sizes and labels to what you’d like. Visit the WordPress Codex for more information on the add_image_size() function:

// Additional Image size

add_image_size('widescreen', 750, 425, false);

add_filter('image_size_names_choose','your_custom_image_sizes');

function your_custom_image_sizes($sizes) {
    return array_merge($sizes, array('widescreen' => 'Widescreen'));
}

Customizing WordPress Jetpack Related Posts

Updated: 12/03/2016 | View post

WordPress’ Jetpack Related Posts module is the best solution in displaying related posts because it doesn’t tax your server resources instead, all the work is done on WordPress.

Remove the related posts CSS:

My problem with JP related posts is how they display related posts and the fact that it includes an addition CSS file which means another http request thus slowing down the site slightly. I’d rather use my own styles and include them in my theme.

Here’s the codes I found to do this. Place these in your functions.php file:

 add_filter( 'jetpack_implode_frontend_css', '__return_false' );
 
 // Then, remove each CSS file, one at a time
 function yourprefix_remove_all_jp_css() {
 wp_deregister_style( 'jetpack_related-posts' ); //Related Posts
 }
 add_action('wp_print_styles', 'yourprefix_remove_all_jp_css' );

source: css-tricks.com

Change the number of related posts to display:

function jetpackme_more_related_posts( $options ) {
    $options['size'] = 6;
    return $options;
}add_filter( 'jetpack_relatedposts_filter_options', 'jetpackme_more_related_posts' );

Position the related posts elsewhere:

First, add this to your functions.php file:

// remove the related posts from default position:

function jetpackme_remove_rp() {
    if ( class_exists( 'Jetpack_RelatedPosts' ) ) {
        $jprp = Jetpack_RelatedPosts::init();
        $callback = array( $jprp, 'filter_add_target_to_dom' );
        remove_filter( 'the_content', $callback, 40 );
    }
} add_filter( 'wp', 'jetpackme_remove_rp', 20 );

Second, add this code where you want the posts to appear in your theme’s single.php file:

<?php if ( class_exists( 'Jetpack_RelatedPosts' ) ) { echo do_shortcode( '[jetpack-related-posts]' ); } ?>

Alter the heading for related posts.

I can change the text and the markup around it. I can place this in my functions.php file:

function jetpackme_related_posts_headline( $headline ) {
$headline = sprintf('<h3 class="jp-relatedposts-headline"><em>%s</em></h3>', esc_html( 'My New Heading' ));
return $headline; } add_filter( 'jetpack_relatedposts_filter_headline', 'jetpackme_related_posts_headline' );

Change the thumbnail size for the related posts:

Just change the highlighted numbers below to the dimensions you want.

// change thumbnail size
function jetpackchange_image_size ( $thumbnail_size ) {
 $thumbnail_size['width'] = 226;
 $thumbnail_size['height'] = 339;
// $thumbnail_size['crop'] = true;
 return $thumbnail_size;
}
add_filter( 'jetpack_relatedposts_filter_thumbnail_size', 'jetpackchange_image_size' );

Remove post tags and category info under each related post:

// remove category and tag context text
add_filter( 'jetpack_relatedposts_filter_post_context', '__return_empty_string' );

For more customization, visit the Jetpack’s Related Posts page.

Here’s some basic styling I use

.jp-relatedposts-post-excerpt, 
.jp-relatedposts-post-date, 
.jp-relatedposts-post-context { display:none;}

body .jp-relatedposts h2 { margin-bottom: 1rem; font-size: 1rem; text-transform: uppercase;
 padding-top: 0.5rem; border-top: solid 3px #222; margin-top: 3rem;}

.jp-relatedposts-items { display:block; white-space:nowrap; 
width: calc(100% + 1.5em); margin-left: -0.75em; }

.jp-relatedposts-post { 
display:inline-block; width:33.33%; 
white-space:normal; vertical-align:top; padding: 0 0.75em; }

@media screen and (max-width: 600px) {
.jp-relatedposts-post { width:200px }
.jp-relatedposts-items { overflow-x:scroll; }
}

Alter the amount of posts that are displayed

Updated: 09/04/2016 | View post

By default WordPress displays all homepage, categories, post archives, tags and custom post archives based on the number you set in the admin page. But what if you want different amounts to display for different pages? Drop this in your functions file:

function modify_num_posts($query) {
if ($query->is_main_query() && $query->is_tax('series') && !is_admin())
$query->set('posts_per_page', 20); }
add_action('pre_get_posts', 'modify_num_posts');

In the snippet above, I’m altering the post output for the taxonomy called “series” and I’m saying I want only 20 posts to display per page. For other kinds of pages, you can use these alternatives:

  • All archive pages: is_archive()
  • Custom post type archives: is_post_type_archive('custom-name')
  • Categories:is_category()
  • Tags: is_tag()

Alter the display of the post count number in WordPress categories

Updated: 09/04/2016 | View post

Drop this in your functions file. In the snippet below, I remove the default parentheses around post count numbers and replace them with span tags. This makes it easier for me to style.

add_filter('wp_list_categories', 'alter_span_cat_count_output');
  function alter_span_cat_count_output($links) {
  $links = str_replace('</a> (', '</a> <span>', $links);
  $links = str_replace(')', '</span>', $links);
  return $links;
}

Change the WordPress excerpt length

Updated: 09/04/2016 | View post

Drop this in your functions file. Change the number to how many words you want to display before the excerpt is truncated with a “read more” link.

function custom_excerpt_length( $length ) { return 30; }
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

Display something only on the last page of a paginated post

Updated: 09/04/2016 | View post

In a project of mine, I only wanted Jetpack’s Related Posts to display on the last page of a paginated post. There was no need for the reader to see related posts at the end of each segment if the reader hadn’t reached the last segment of the post. To make this happen, I found this useful code:

<?php /* Only show on the last page if post is paginated */
global $page; global $numpages; if( $page == $numpages ) :?>

   <?php // put whatever you want here ?>

<?php endif;?>

Automatic link to blog post page

Updated: 08/26/2016 | View post

Add this code to your functions.php file:

// Generate Link to posts page
function archi_get_post_page_url() {
  if( 'page' == get_option( 'show_on_front' ) ) {
    return get_permalink( get_option('page_for_posts' ) );
  } else { return home_url();}
}

And then in your theme file where you want the link to display:

<a href="<?php echo archi_get_post_page_url();?>">Back to all post page</a>

How to do a search and replace in phpMyAdmin for WordPress

Updated: 12/24/2016 | View post

mysql

Find the SQL tab and paste the following in the command box.

In the example below, I’m searching the WordPress table post_content to find and replace something. Change the information between the quotes ‘Item to replace here‘ with what you want to find and change the information between the quotes ‘Replacement text here‘ with what you want to replace. Then click “Go.”

UPDATE wp_posts SET post_content = REPLACE (
post_content,
'Item to replace here',
'Replacement text here');

Note: Depending on your WordPress setup, your wp_posts may have a prefix, like abc_wp_posts but normally the first is the default name of the table. However, post_content doesn’t change.

Automatically number each post in WordPress

Updated: 07/02/2016 | View post

In some cases I need to automatically number each post starting with the very first being number one. I’m not talking about using post ID here, but actual number in order of post date. Here’s the code I found that will work with any post type. Notice the post type I’m number is “podcast.” Change that to whatever post type you want to number. Add the below code to your functions.php file.

function updateNumbers() {
 /* numbering the published posts, starting with 1 for oldest;
 / creates and updates custom field 'incr_number';
 / to show in post (within the loop) use <?php echo get_post_meta($post->ID,'incr_number',true); ?>
 / alchymyth 2010 */
 global $wpdb;
 $querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts 
 WHERE $wpdb->posts.post_status = 'publish' 
 AND $wpdb->posts.post_type = 'podcast' 
 ORDER BY $wpdb->posts.post_date ASC";
 $pageposts = $wpdb->get_results($querystr, OBJECT);
 $counts = 0 ;
 if ($pageposts):
 foreach ($pageposts as $post):
 $counts++;
 add_post_meta($post->ID, 'incr_number', $counts, true);
 update_post_meta($post->ID, 'incr_number', $counts);
 endforeach;
endif;
}

add_action ( 'publish_post', 'updateNumbers', 11 );
add_action ( 'deleted_post', 'updateNumbers' );
add_action ( 'edit_post', 'updateNumbers' );

Add the following highlighted function to your theme files where you want the number to display. For example:

<h1>Episode <?php echo get_post_meta($post->ID,'incr_number',true); ?>: <?php the_title();?></h1>

After this, update a post to see the numbers added to each post. If you don’t update one post, you will not see the changes until the next time you edit or publish a post.

Displaying user info

Updated: 05/15/2016 | View post

Get current user’s info:

<?php
    $current_user = wp_get_current_user(); // set variable
    echo 'Username: ' . $current_user->user_login . '<br />';
    echo 'User email: ' . $current_user->user_email . '<br />';
    echo 'User first name: ' . $current_user->user_firstname . '<br />';
    echo 'User last name: ' . $current_user->user_lastname . '<br />';
    echo 'User display name: ' . $current_user->display_name . '<br />';
    echo 'User ID: ' . $current_user->ID . '<br />';
    echo 'User Gravatar: ' . get_avatar( $current_user->ID, 80 ); // the number is the size of the avatar
?>

Conditional statements for logged in users:

<?php if (is_user_logged_in()): // if logged in ?> ... <?php endif; ?> 

<?php if (! is_user_logged_in()): // if logged out ?> ... <?php endif; ?>

Create a link to the logged in user’s author page:

<a href="<?php $current_user = wp_get_current_user(); 
echo 'http://website.com/author/'.$current_user->user_login ?>">View Profile</a>

// User logout link

<a href="<?php echo wp_logout_url(); ?>">Log Out</a>

Change the author base from “author” to something else. In this example, I changed it to “profile”. Add this to your functions.php file:

// Author slug change

add_action('init', 'change_author_base');
function change_author_base() {
  global $wp_rewrite;
  $author_slug = 'profile'; // change slug name
  $wp_rewrite->author_base = $author_slug;
}

List all the children of parent page

Updated: 05/13/2016 | View post

When you visit the parent page, it will list all its children. Visiting the child page of the parent will show its siblings.

<?php if($post->post_parent)
   $children = wp_list_pages("sort_column=menu_order&title_li=&depth=1&child_of=".$post->post_parent."&echo=0");
   else $children = wp_list_pages("sort_column=menu_order&title_li=&depth=1&child_of=".$post->ID."&echo=0");
   if ($children): ?>
   <ul>
     <?php echo $children; ?>
   </ul>
<?php endif; ?>

WordPress cheat sheet

Updated: 05/13/2016 | View post

For more WordPress theme snippets visit this old post of mine:

WordPress Cheatsheet

List posts by Category

Updated: 05/15/2016 | View post

What this does is prints out the heading of each category and lists only the posts in that category. Fill free to alter the loop to your needs, but keep the 'cat' => $cat_id, this is necessary for it to work. This doesn’t support pagination.

<?php
 $cats = get_categories(); foreach ($cats as $cat) {
    $cat_id= $cat->term_id;
    echo "<h2>".$cat->name."</h2>";

    query_posts( array('cat' => $cat_id, 'posts_per_page' => -1, 'post_type' => 'post'));
    if (have_posts()) : while (have_posts()) : the_post(); ?>

    <?php // stuff for the loop goes here... ?>
 
    <?php endwhile; endif; ?>
 <?php } ?>

Add inline javascript to WordPress correctly

Updated: 05/13/2016 | View post

Add to functions.php file. Name the add_action whatever. You can also have the script load in the footer by changing wp_head to wp_footer.

// Add JS to Head
 
 add_action('wp_head','spd_add_cart_link');
 function spd_add_cart_link() { // break out of php ?>
 <script>
   // javascripts here
 </script>
 <?php } // break back into php

Source link

Get the current page order number according to WordPress

Updated: 05/13/2016 | View post

This is useful for book chapter numbering if you don’t want to manually add the page number of a child in the title or wherever else: Example usage:

<h1>Chapter <?php echo $post->menu_order;?></h1>

Get the current page and total number of pages in a paginated post in WordPress

Updated: 05/13/2016 | View post

<?php global $multipage; global $numpages; global $page; ?>

<?php if ($multipage):?>
<div class="page-numbering">Page <?php echo $page; ?> of <?php echo $numpages; ?></div>
<?php endif; ?>

This will print out: Page 1 of 3

Remove admin menu items from WordPress

Updated: 05/13/2016 | View post

Add and alter the highlighted items to whatever admin pages you want to hide. This removes them for all users. For more flexibility and less coding, use a plugin.

function remove_admin_menu_items() {
 $remove_menu_items = array(__('Links'),__('Posts'),__('Comments'));
 global $menu;
 end ($menu);
 while (prev($menu)){
 $item = explode(' ',$menu[key($menu)][0]);
 if(in_array($item[0] != NULL?$item[0]:"" , $remove_menu_items)){
 unset($menu[key($menu)]);}
 }
 }
 
 add_action('admin_menu', 'remove_admin_menu_items');

Conditional Statement: if the children of this parent page

Updated: 05/13/2016 | View post

Sometimes all you want to do is write a statement for every child of a particular parent page. Instead of listing all the ID for each child page in an array, just use this code and replace the number ID with parent ID of the child pages:

<?php if (in_array(60, $post->ancestors)): ?>
    <?php // but your statements here ?>
<?php endif; ?>

Get the url to your theme directory

Updated: 05/13/2016 | View post

<?php echo get_stylesheet_directory_uri(); ?>

Here is a usage example for grabbing an image from your theme files’ image directory:

<img 
src="<?php echo get_stylesheet_directory_uri(); ?>/img/imagefile.jpg" 
alt="image-title" 
width="100" 
height="50" />