Welcome to Codex
List of commonly used code snippets for HTML, JavaScript, WordPress, ACF WordPress Plugin

HTML

Flexbox Structure

This is flexbox structure for HTML.

<div class="site-flex is--padded is--center-aligned">
	<div class="flex__col is--col-50">50_percent_column</div>
	<div class="flex__col is--col-50">50_percent_column</div>
</div>

CSS-Grid Structure

This is CSS-Grid structure for HTML.

<div class="site-grid is--gap-24 is--center-aligned">
	<div class="grid__col-12 grid__col-md-6">Col_md_6</div>
	<div class="grid__col-12 grid__col-md-6">Col_md_6</div>
</div>

JavaScript

document.ready

-

$(document).ready(function() {
});

Hide navigation on scroll

-

	// add class to header to show hide on page scroll
	var prevScrollpos = window.pageYOffset;
	window.onscroll = function() {
		var currentScrollPos = window.pageYOffset;
		var header = document.getElementById("masthead");
		if (prevScrollpos > currentScrollPos || currentScrollPos <= 30) {
			jQuery(header).removeClass('scrollDown'); /* Show Menu */
		} else if (prevScrollpos + 25 < currentScrollPos) {
			jQuery(header).addClass('scrollDown'); /* Hide Menu */
		}
		prevScrollpos = currentScrollPos;
	}

CSS

header#masthead.scrollDown,
body.admin-bar header#masthead.scrollDown {
	top: -98px;
}

PHP

Lowercase string or vaariable

-

<?php echo strtolower("Hello WORLD."); ?>

WordPress

Add External CSS & JS

-

	// Slick Slider CSS
	wp_enqueue_style( 'slick-css', get_template_directory_uri() . '/assets/css/slick.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'slick-themecss', get_template_directory_uri() . '/assets/css/slick-theme.css', array(), rand(111,9999), 'all' );

	//FontAwesome Icon Fonts
	wp_enqueue_style( 'font-awesome-css', get_template_directory_uri() . '/assets/css/font-awesome.css', array(), rand(111,9999), 'all' );

	//Temporary 
	wp_enqueue_style( 'custom_theme-font-and-colors', get_template_directory_uri() . '/assets/css/00colors.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-html-body', get_template_directory_uri() . '/assets/css/01html_body.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-default-resets', get_template_directory_uri() . '/assets/css/02default_resets.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-layout-and-strucure', get_template_directory_uri() . '/assets/css/03layout_stucture.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-typography', get_template_directory_uri() . '/assets/css/04typography.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-utilities', get_template_directory_uri() . '/assets/css/05utilities.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-forms', get_template_directory_uri() . '/assets/css/06fomrs.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-header', get_template_directory_uri() . '/assets/css/07header.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-footer', get_template_directory_uri() . '/assets/css/08footer.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-blog', get_template_directory_uri() . '/assets/css/09blog.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-paginations', get_template_directory_uri() . '/assets/css/10paginations.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-post-contents', get_template_directory_uri() . '/assets/css/11post_content.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-acf-blocks', get_template_directory_uri() . '/assets/css/12acf_blocks.css', array(), rand(111,9999), 'all' );	
	wp_enqueue_style( 'custom_theme-jscomponents', get_template_directory_uri() . '/assets/css/13jscomponents.css', array(), rand(111,9999), 'all' );
	wp_enqueue_style( 'custom_theme-styleguide', get_template_directory_uri() . '/assets/css/14styleguide.css', array(), rand(111,9999), 'all' );

	//Custom Theme CSS
	wp_enqueue_style( 'custom_theme', get_template_directory_uri() . '/assets/css/custom_theme.css', array(), rand(111,9999), 'all' );

	//Default jQuery Library
	wp_enqueue_script( 'jquery-js', 'https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array(), '1.0.0', 'true' );

	//GSAP Library
	wp_enqueue_script( 'gsap-js', 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js', array(), '1.0.0', 'true' );
	wp_enqueue_script( 'scrollTrigger-js', 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js', array(), '1.0.0', 'true' );

	//Smooth Scroll
	wp_enqueue_script( 'lenis-js', 'https://cdn.jsdelivr.net/gh/studio-freight/lenis@1/bundled/lenis.min.js', array(), '1.0.0', 'true' );

	//Main Navigation Scroll Effects
	wp_enqueue_script( 'waypoints-js', get_template_directory_uri() . '/assets/js/waypoints.min.js', array(), '1.0.0', 'true' );

	// Slick Slider JS
	wp_enqueue_script( 'slick-js', get_template_directory_uri() . '/assets/js/slick.min.js', array(), '1.0.0', 'true' );

	//Custom Theme JS
	wp_enqueue_script( 'custom_theme-js', get_template_directory_uri() . '/assets/js/custom_theme.js', array(), '1.0.0', 'false' );

Get site URL

-

<?php echo get_home_url(); ?>

Get template URL

-

<?php echo get_template_directory_uri(); ?>

Get post title

-

<?php the_title(); ?>

Get post content

-

<?php the_content(); ?>

Get post excerpt

-

<?php the_excerpt();?>

Get post featured imaage as background

-

<?php if (has_post_thumbnail( $post->ID ) ): ?>
    <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
    <div id="custom-bg" style="background-image: url('<?php echo $image[0]; ?>')"></div>
<?php endif; ?>

Get post featured image as img tag

-

<?php 
    if ($buildingimg = has_post_thumbnail() ) {
		echo get_the_post_thumbnail( get_the_ID(), 'full', array(
		'alt' => get_the_title(),
    } else {
        echo "<img src=". get_template_directory_uri()."/assets/images/no_image.png' />"; }
?>

Get navigation menu

-

<?php 
  wp_nav_menu(
    array(
      'menu_id'        => 'Menu name', //Menu Name
      'menu_class'	=> 'menu list-inline',
      )
  );
?>

Add "/blogs/" to blog post urls (Option 1)

-


/* Rewrite WordPress URLs to Include /blogs/ in Post Permalink Structure */
function custom_blog_generate_rewrite_rules( $wp_rewrite ) {
  $new_rules = array(
    '(([^/]+/)*blog)/page/?([0-9]{1,})/?$' => 'index.php?pagename=$matches[1]&paged=$matches[3]',
    'blogs/([^/]+)/?$' => 'index.php?post_type=post&name=$matches[1]',
    'blogs/[^/]+/attachment/([^/]+)/?$' => 'index.php?post_type=post&attachment=$matches[1]',
    'blogs/[^/]+/attachment/([^/]+)/trackback/?$' => 'index.php?post_type=post&attachment=$matches[1]&tb=1',
    'blogs/[^/]+/attachment/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',
    'blogs/[^/]+/attachment/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',
    'blogs/[^/]+/attachment/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?post_type=post&attachment=$matches[1]&cpage=$matches[2]',		
    'blogs/[^/]+/attachment/([^/]+)/embed/?$' => 'index.php?post_type=post&attachment=$matches[1]&embed=true',
    'blogs/[^/]+/embed/([^/]+)/?$' => 'index.php?post_type=post&attachment=$matches[1]&embed=true',
    'blogs/([^/]+)/embed/?$' => 'index.php?post_type=post&name=$matches[1]&embed=true',
    'blogs/[^/]+/([^/]+)/embed/?$' => 'index.php?post_type=post&attachment=$matches[1]&embed=true',
    'blogs/([^/]+)/trackback/?$' => 'index.php?post_type=post&name=$matches[1]&tb=1',
    'blogs/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&name=$matches[1]&feed=$matches[2]',
    'blogs/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&name=$matches[1]&feed=$matches[2]',
    'blogs/page/([0-9]{1,})/?$' => 'index.php?post_type=post&paged=$matches[1]',
    'blogs/[^/]+/page/?([0-9]{1,})/?$' => 'index.php?post_type=post&name=$matches[1]&paged=$matches[2]',
    'blogs/([^/]+)/page/?([0-9]{1,})/?$' => 'index.php?post_type=post&name=$matches[1]&paged=$matches[2]',
    'blogs/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?post_type=post&name=$matches[1]&cpage=$matches[2]',
    'blogs/([^/]+)(/[0-9]+)?/?$' => 'index.php?post_type=post&name=$matches[1]&page=$matches[2]',
    'blogs/[^/]+/([^/]+)/?$' => 'index.php?post_type=post&attachment=$matches[1]',
    'blogs/[^/]+/([^/]+)/trackback/?$' => 'index.php?post_type=post&attachment=$matches[1]&tb=1',
    'blogs/[^/]+/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',
    'blogs/[^/]+/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',
    'blogs/[^/]+/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?post_type=post&attachment=$matches[1]&cpage=$matches[2]',
  );
  $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'custom_blog_generate_rewrite_rules' );

function custom_update_post_link( $post_link, $id = 0 ) {
  $post = get_post( $id );
  if( is_object( $post ) && $post->post_type == 'post' ) {
    return home_url( '/blogs/' . $post->post_name );
  }
  return $post_link;
}
add_filter( 'post_link', 'custom_update_post_link', 1, 3 );
		

Add "/blogs/" to blog post urls (Option 2)

-


/*Add "/blogs/" to blog post urls */
function blog_post_url_add_rewrite_rules( $wp_rewrite )
{
    $new_rules = [
        'blogs/page/([0-9]{1,})/?$' => 'index.php?post_type=post&paged='. $wp_rewrite->preg_index(1),
        'blogs/(.+?)/?$' => 'index.php?post_type=post&name='. $wp_rewrite->preg_index(1),
    ];
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    return $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'blog_post_url_add_rewrite_rules');

function blog_post_url_update_links($post_link, $id=0){
    $post = get_post($id);
    if( is_object($post) && $post->post_type == 'post'){
        return home_url('/blogs/'. $post->post_name.'/');
    }
    return $post_link;
}
add_filter('post_link', 'blog_post_url_update_links', 1, 3);
		

Query for Custom Post Type

-

<?php
    $args = array(
    'post_type'   => 'post-type-name', // Custom Post Type Name.
    'showposts' => '-1', // Number of post to show, -1 for all post.
    'orderby'   => 'meta_value',
    'order' => 'ASC', //ASC | DESC.
);
$post-type-name = new WP_Query( $args ); ?>

<?php if( $post-type-name->have_posts() ) : ?>
    <ul class="list-inline">
        <?php while( $post-type-name->have_posts() ) : $post-type-name->the_post(); ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php endwhile; wp_reset_postdata(); ?>
    </ul>
<?php endif; ?>

Query for Custom Post Type - Do not include Current post

-

<?php
    $currentID = get_the_ID();
    $args = array(
    'post_type'   => 'post-type-name', // Custom Post Type Name.
    'showposts' => '-1', // Number of post to show, -1 for all post.
    'orderby'   => 'meta_value',
    'order' => 'ASC', //ASC | DESC.
    'post__not_in' => array( $currentID ),

);
$post-type-name = new WP_Query( $args ); ?>

<?php if( $post-type-name->have_posts() ) : ?>
    <ul class="list-inline">
        <?php while( $post-type-name->have_posts() ) : $post-type-name->the_post(); ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php endwhile; wp_reset_postdata(); ?>
    </ul>
<?php endif; ?>

Page slug as body class

funtion.php

/*
Page Slug to Body Class
*/
function add_slug_body_class( $classes ) {
	global $post;
		if ( isset( $post ) ) {
			$classes[] = $post->post_type . '-' . $post->post_name;
		}
	return $classes;
}
add_filter( 'body_class', 'add_slug_body_class' );

Breadcrumb

funtion.php

function the_breadcrumb()
{
    $showOnHome = 0; // 1 - show breadcrumbs on the homepage, 0 - don't show
    $delimiter = '&raquo;'; // delimiter between crumbs
    $home = 'Home'; // text for the 'Home' link
    $showCurrent = 1; // 1 - show current post/page title in breadcrumbs, 0 - don't show
    $before = '<span class="current">'; // tag before the current crumb
    $after = '</span>'; // tag after the current crumb

    global $post;
    $homeLink = get_bloginfo('url');
    if (is_home() || is_front_page()) {
        if ($showOnHome == 1) {
            echo '<div id="crumbs"><a href="' . $homeLink . '">' . $home . '</a></div>';
        }
    } else {
        echo '<div id="crumbs"><a href="' . $homeLink . '">' . $home . '</a> ' . $delimiter . ' ';
        if (is_category()) {
            $thisCat = get_category(get_query_var('cat'), false);
            if ($thisCat->parent != 0) {
                echo get_category_parents($thisCat->parent, true, ' ' . $delimiter . ' ');
            }
            echo $before . 'Archive by category "' . single_cat_title('', false) . '"' . $after;
        } elseif (is_search()) {
            echo $before . 'Search results for "' . get_search_query() . '"' . $after;
        } elseif (is_day()) {
            echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
            echo '<a href="' . get_month_link(get_the_time('Y'), get_the_time('m')) . '">' . get_the_time('F') . '</a> ' . $delimiter . ' ';
            echo $before . get_the_time('d') . $after;
        } elseif (is_month()) {
            echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
            echo $before . get_the_time('F') . $after;
        } elseif (is_year()) {
            echo $before . get_the_time('Y') . $after;
        } elseif (is_single() && !is_attachment()) {
            if (get_post_type() != 'post') {
                $post_type = get_post_type_object(get_post_type());
                $slug = $post_type->rewrite;
                echo '<a href="' . $homeLink . '/' . $slug['slug'] . '/">' . $post_type->labels->singular_name . '</a>';
                if ($showCurrent == 1) {
                    echo ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
                }
            } else {
                $cat = get_the_category();
                $cat = $cat[0];
                $cats = get_category_parents($cat, true, ' ' . $delimiter . ' ');
                if ($showCurrent == 0) {
                    $cats = preg_replace("#^(.+)\s$delimiter\s$#", "$1", $cats);
                }
                echo $cats;
                if ($showCurrent == 1) {
                    echo $before . get_the_title() . $after;
                }
            }
        } elseif (!is_single() && !is_page() && get_post_type() != 'post' && !is_404()) {
            $post_type = get_post_type_object(get_post_type());
            echo $before . $post_type->labels->singular_name . $after;
        } elseif (is_attachment()) {
            $parent = get_post($post->post_parent);
            $cat = get_the_category($parent->ID);
            $cat = $cat[0];
            echo get_category_parents($cat, true, ' ' . $delimiter . ' ');
            echo '<a href="' . get_permalink($parent) . '">' . $parent->post_title . '</a>';
            if ($showCurrent == 1) {
                echo ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
            }
        } elseif (is_page() && !$post->post_parent) {
            if ($showCurrent == 1) {
                echo $before . get_the_title() . $after;
            }
        } elseif (is_page() && $post->post_parent) {
            $parent_id  = $post->post_parent;
            $breadcrumbs = array();
            while ($parent_id) {
                $page = get_page($parent_id);
                $breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
                $parent_id  = $page->post_parent;
            }
            $breadcrumbs = array_reverse($breadcrumbs);
            for ($i = 0; $i < count($breadcrumbs); $i++) {
                echo $breadcrumbs[$i];
                if ($i != count($breadcrumbs)-1) {
                    echo ' ' . $delimiter . ' ';
                }
            }
            if ($showCurrent == 1) {
                echo ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
            }
        } elseif (is_tag()) {
            echo $before . 'Posts tagged "' . single_tag_title('', false) . '"' . $after;
        } elseif (is_author()) {
            global $author;
            $userdata = get_userdata($author);
            echo $before . 'Articles posted by ' . $userdata->display_name . $after;
        } elseif (is_404()) {
            echo $before . 'Error 404' . $after;
        }
        if (get_query_var('paged')) {
            if (is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author()) {
                echo ' (';
            }
            echo __('Page') . ' ' . get_query_var('paged');
            if (is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author()) {
                echo ')';
            }
        }
        echo '</div>';
    }
}

template-file.php

<?php if (function_exists('the_breadcrumb')) the_breadcrumb(); ?>

Single Page Navigation

-

<nav class="single-post-navigation">
			<?php
				$prev_post = get_previous_post();
				$next_post = get_next_post();
			?>

			<div class="nav-next">
				<?php if ( is_a( $next_post, 'WP_Post' ) ) : ?>
					<?php
						$next_permalink = get_permalink( $next_post->ID );
					?>
					<?php next_post_link( '%link', __( '<span class="meta-nav">&larr;</span> Next' ) ); ?> 
					<h6 class="fs-lg fw-600">
						<a href="<?php echo esc_url( $next_permalink ); ?>" title="<?php echo esc_attr( $next_post->post_title ); ?>">
							<?php echo esc_html( $next_post->post_title ); ?>
						</a>
					</h6>
				<?php endif; ?>
			</div>

			<div class="nav-previous">
				<?php if ( is_a( $prev_post, 'WP_Post' ) ) : ?>
					<?php
						$previous_permalink = get_permalink( $prev_post->ID );
					?>
					<?php previous_post_link( '%link', __( 'Previous <span class="meta-nav">&rarr;</span>' ) ); ?> 
					<h6 class="fs-lg fw-600">
						<a href="<?php echo esc_url( $previous_permalink ); ?>" title="<?php echo esc_attr( $prev_post->post_title ); ?>">
							<?php echo esc_html( $prev_post->post_title ); ?>
						</a>
					</h6>
				<?php endif; ?>
			</div>
		</nav>

Default sorting for Custom Post Types

function.php

function custom_posts_retreats($query) {
	if ( !is_admin() && $query->is_main_query() ) {
		if (is_post_type_archive('retreats')) {
			$query->set('orderby', 'date' );
			$query->set('order', 'ASC' );
		}
	}
}

add_action('pre_get_posts','custom_posts_retreats');

ACF Plugin

Add option page

-

/**
 * Option page.
*/
if( function_exists('acf_add_options_page') ) {
  acf_add_options_page(array(
    'page_title'  => 'General Information',
    'menu_title'  => 'General Info',
    'menu_slug'   => 'general-information',
    'capability'  => 'edit_posts',
    'position'    => 4,
    'redirect'    => false
  ));
}
/**/

Groups or Repeater Field

-

<?php if( have_rows('hero') ): ?>
  <?php while( have_rows('hero') ): the_row(); 

    // Get sub field values.
    $image = get_sub_field('image');
    $link = get_sub_field('link');

  ?>
    <div class="hero">
      <img src="<?php echo esc_url( $image['url'] ); ?>" alt="<?php echo esc_attr( $image['alt'] ); ?>" />
      <div class="content">
        <?php the_sub_field('caption'); ?>
        <a href="<?php echo esc_url( $link['url'] ); ?>"><?php echo esc_attr( $link['title'] ); ?></a>
      </div>
    </div>
  <?php endwhile; ?>
<?php endif; ?>

Empty Field

-

<?php if( get_field('field_name') ): ?>
    <p>My field value: <?php the_field('field_name'); ?></p>
<?php endif; ?>