All WordPress snippets
Want your own copy?
Fork this repo and build your own snippet collection. Fork on GitHub →
WordPress
Basic Open Graph Meta Tags for Single Posts
Outputs Open Graph title, description, and image tags on single posts — useful groundwork if you're not running an SEO plugin yet.
php
/**
* Add Open Graph Meta Tags
*/
function meta_og() {
global $post;
if ( is_single() ) {
if( has_post_thumbnail( $post->ID ) ) {
$img_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );
}
$excerpt = strip_tags( $post->post_content );
$excerpt_more = '';
if ( strlen($excerpt ) > 155) {
$excerpt = substr( $excerpt,0,155 );
$excerpt_more = ' ...';
}
$excerpt = str_replace( '"', '', $excerpt );
$excerpt = str_replace( "'", '', $excerpt );
$excerptwords = preg_split( '/[nrt ]+/', $excerpt, -1, PREG_SPLIT_NO_EMPTY );
array_pop( $excerptwords );
$excerpt = implode( ' ', $excerptwords ) . $excerpt_more; ?>
<meta name="author" content="Your Name">
<meta name="description" content="<?php echo $excerpt; ?>">
<meta property="og:title" content="<?php echo the_title(); ?>">
<meta property="og:description" content="<?php echo $excerpt; ?>">
<meta property="og:type" content="article">
<meta property="og:url" content="<?php echo the_permalink(); ?>">
<meta property="og:site_name" content="Your Site Name">
<meta property="og:image" content="<?php echo $img_src[0]; ?>"><?php
} else {
return;
}
}
add_action('wp_head', 'meta_og', 5);
More WordPress snippets
Register and Output a Custom Nav Menu
Adds a new menu location you can assign in Appearance → Menus, shows how to output it in a template, and includes the multi-menu version too.
Define a Reusable Global String
A simple pattern for storing a value — like a phone number or address — in one place and reusing it anywhere in your theme.
Auto-Escape HTML Typed Inside Code Tags
Makes sure any markup typed inside <code> or <tt> tags in the editor gets escaped automatically, so it displays as visible text instead of being rendered as real HTML.