I’ve built a lot of custom WordPress themes over the years and always find myself digging through past projects to find certain snippets of PHP code. To put it all in one place for myself and others, below are a bunch of random PHP snippets (a lot of these are already included in my WP theme starter that I use to start all my WP themes).

Register menu

function register_main_menu() {
  register_nav_menu('header-menu',__( 'Header Menu' ));
}

add_action( 'init', 'register_main_menu' );

Display menu

 'header-menu', 'menu_class' => 'nav-list', 'container' => '' ) ); ?>

Create custom post type

add_action( 'init', 'create_post_types' );

function create_post_types() {
  register_post_type( 'events',
    array(
      'labels' => array(
        'name' => __( 'Events' ),
        'singular_name' => __( 'Event' )
      ),
      'public' => true,
      'has_archive' => true,
      'rewrite' => true,
      'supports' => array( 'title', 'editor', 'thumbnail' )
    )
  );
}

Add theme support for thumbnails

add_theme_support( 'post-thumbnails', array('post', 'page', 'events') );

Create custom thumbnail size

add_image_size( 'name', 966, 525, array('center', 'center') );

Remove WP emoji stuff

remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );

Display theme path

echo get_template_directory_uri();

Site URL helper

function url () {
  print bloginfo('url');
}

Simple loop

if ( have_posts() ) {
  while ( have_posts() ) {
    the_post();
  }
}

Simple loop - inline

if ( have_posts() ) : while ( have_posts() ) : the_post();

Custom loop

$args = array( 'post_type' => 'podcast', 'posts_per_page' => 10 );

$query = new WP_Query( $args );
if ( $query->have_posts() ) {
  while ( $query->have_posts() ) {
    $query->the_post();
  }
}

Display featured image

the_post_thumbnail('custom-size');

Display featured image from specific post

echo get_the_post_thumbnail(35);

Display post date

echo get_the_date('M j, Y');

Include a partial

include( locate_template( 'partials/sidebar.php' ) );

Display current year

echo date('Y');

Display site name

bloginfo('name');