Skip to content

Instantly share code, notes, and snippets.

@andrejIka
Forked from yagopv/gist:8470185
Created June 19, 2020 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrejIka/12fc4ae7c9af4175838456b897be4599 to your computer and use it in GitHub Desktop.
Save andrejIka/12fc4ae7c9af4175838456b897be4599 to your computer and use it in GitHub Desktop.
Wordpress Snippets

###Custom Post Types

Docs

function codex_custom_init() {
  $labels = array(
    'name'               => 'Books',
    'singular_name'      => 'Book',
    'add_new'            => 'Add New',
    'add_new_item'       => 'Add New Book',
    'edit_item'          => 'Edit Book',
    'new_item'           => 'New Book',
    'all_items'          => 'All Books',
    'view_item'          => 'View Book',
    'search_items'       => 'Search Books',
    'not_found'          => 'No books found',
    'not_found_in_trash' => 'No books found in Trash',
    'parent_item_colon'  => '',
    'menu_name'          => 'Books'
  );

  $args = array(
    'labels'             => $labels,
    'public'             => true,
    'publicly_queryable' => true,
    'show_ui'            => true,
    'show_in_menu'       => true,
    'query_var'          => true,
    'rewrite'            => array( 'slug' => 'book' ),
    'capability_type'    => 'post',
    'has_archive'        => true,
    'hierarchical'       => false,
    'menu_position'      => null,
    'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
  );

  register_post_type( 'book', $args );
}
add_action( 'init', 'codex_custom_init' );

###Custom Taxonomies

function create_my_taxonomies() {
	register_taxonomy('actors', 'post', array(
	'hierarchical' => false, 'label' => 'Actors',
	'query_var' => true, 'rewrite' => true));
	register_taxonomy('producers', 'post', array(
	'hierarchical' => false, 'label' => 'Producers',
	'query_var' => true, 'rewrite' => true));
}
add_action('init', 'create_my_taxonomies', 0);

With this definition, we get "for free" these links

http://mymoviereviews.com/actor/johnny-depp/ http://mymoviereviews.com/actor/christina-ricci/ http://mymoviereviews.com/producer/scott-rudin http://mymoviereviews.com/producer/adam-schroeder http://mymoviereviews.com/director/tim-burton/ http://mymoviereviews.com/genre/horror-suspense/

By default these links will use archive.php

Tag cloud for custom taxonomy

<?php wp_tag_cloud(array('taxonomy' => 'people', 'number' => 45)); ?>

Query posts in a specific taxonomy. Do it before the loop

<?php query_posts(array('people' => 'will-smith', 'showposts' => 10)); ?>

Show terms linked to a specific taxonomy for a specific post

<?php echo get_the_term_list($post->ID, 'people', 'People: ', ', ', ''); ?>

Include Scripts and Stylesheets

CSS

<link rel='stylesheet' href='<?php bloginfo("stylesheet_url"); ?>' type='text/css' media='screen' />

JS

//For the WP version of jQuery
<?php wp_enqueue_script('jquery'); ?> 

// For any Script
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/myscript.js"></script>

Particular pages

//For including CSS and scripts in particular pages
<?php if (is_page_template('page-archives.php')) { ?>
	<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/archives.css" type="text/css" media="screen" />
	<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/archives.js"></script>
<?php } ?>

or

<?php if (is_page("5")) { ?>
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/archives.css" type="text/css" media="screen" />
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/archives.js"></script>
<?php } ?>

All together using wp_head

<?php wp_enqueue_script('jquery'); ?>
<?php wp_head(); ?> // wp_head will insert all in the <head>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/myscript.js"></script>
<?php if (is_page("5")) { ?>
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/archives.css" type="text/css" media="screen" />
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/archives.js"></script>
<?php } ?>

###Descriptive <title>

Use it in header.php

<title>
	<?php if (function_exists('is_tag') && is_tag()) {
		single_tag_title('Tag Archive for &quot;'); echo '&quot; - ';
	} elseif (is_archive()) {
		wp_title(''); echo ' Archive - ';
	} elseif (is_search()) {
		echo 'Search for &quot;'.wp_specialchars($s).'&quot; - ';
	} elseif (!(is_404()) && (is_single()) || (is_page())) {
		wp_title(''); echo ' - ';
	} elseif (is_404()) {
		echo 'Not Found - ';
	}
	if (is_home()) {
		bloginfo('name'); echo ' - '; bloginfo('description');
	} else {
		bloginfo('name');
	}
	if ($paged > 1) {
		echo ' - page '. $paged;
	} ?>
</title>

Getting Blog information

<?php bloginfo('template_url'); ?>
/*
admin_email, atom_url, charset, comments_atom_url, comments_rss2_url, description, 
url, html_type, language, name, pingback_url, rdf_url, rss2_url, rss_url, siteurl, 
stylesheet_directory, stylesheet_url, template_directory, template_url, text_direction, 
version, wpurl
*/

Add manage Global Custom Fields to Admin

<?php add_action('admin_menu', 'add_gcf_interface');
	function add_gcf_interface() {
		add_options_page('Global Custom Fields', 'Global Custom Fields', '8', 'functions', 'editglobalcustomfields');
	}
	function editglobalcustomfields() { ?>
		<div class="wrap">
			<h2>Global Custom Fields</h2>
			<form method="post" action="options.php">
			<?php wp_nonce_field('update-options') ?>
				<p>
					<strong>Amazon ID:</strong><br />
					<input type="text" name="amazonid" size="45" value="<?php echo get_option('amazonid'); ?>" />
				</p>
				<p>
					<input type="submit" name="Submit" value="Update Options" />
				</p>
				<input type="hidden" name="action" value="update" />
				<input type="hidden" name="page_options" value="amazonid" />
			</form>
		</div>
<?php } ?>

...

<?php echo get_option('amazonid'); ?>

How Wordpress decide what page to show?

Page type Try 1 > Try 2 -
404 404.php > index.php
Search search.php > index.php
Taxonomy taxonomy-{tax}-{term}.php > taxonomy-{tax}.php > taxonomy.php > archive.php > index.php
Home home.php > index.php
Attachment {mime-type}.php > attachment.php > single.php > index.php
Single single-{post-type}.php > single.php > index.php
Page {custom-template}.php > page-{slug}.php > page-{id}.php > page.php > index.php
Category category-{slug}.php > category-{id}.php > category.php > archive.php > index.php
Tag tag-{slug}.php > tag-{id}.php > tag.php > tag.php > index.php
Author author-{author-nicename}.php > author-{author-id}.php > author.php > archive.php > index.php
Date date.php archive.php > index.php
Archive archive.php > index.php

###Theme Files

File Description
404.php Error page, served up when someone goes to a URL on your site that doesn’t exist
archive.php Page that displays posts in one particular day, month, year, category, tag, or author
archives.php Page template that includes search form, category list, and monthly archives (requires page using it)
comments-popup.php If you enable popup comments (obscure function), the comments link will use this template
comments.php This file delivers all the comments, pingbacks, trackbacks, and the comment form when called
footer.php Included at the bottom of every page. Closes off all sections. (Copyright, analytics, etc)
front-page.php Displays content for the site’s front page, aka home page
functions.php File to include special behavior for your theme.
header.php Included at the top of every page. (DOCTYPE, head section, navigation, etc)
home.php Displays content for the site’s front page if front-page.php is not available
image.php If you wish to have unique pages for each of the images on your site (for credits, copyright…)
index.php This is typically the “homepage” of your blog, but also the default should any other views be missing
links.php Special page template for a home for your blogroll
loop.php Common in newer themes, an optional file to house your custom, multiple, or regular loops
page.php Template for Pages, the WordPress version of static-style/non-blog content
rtl.css A special CSS file for your optional inclusion to accommodate “right to left” languages
screenshot.png This is the image thumbnail of your theme, for help distinguishing it in the Appearance picker
search.php The search results page template
sidebar.php Included on pages where/when/if you want a sidebar
single.php This file is displays a single Post in full (the Posts permalink), typically with comments
style.css The styling information for your theme, required for your theme to work, even if you don’t use it

###Plugins

VaultPress

VaultPress is a plugin and a paid service from Automattic, the creators of WordPress. Once set up, your entire blog is backed up to “the cloud” including all files on the server (WordPress core, themes, plugins, images, etc.) and the database. They offer a premium-level service that includes scanning your files for possible

Art Direction

This plugin allows you to insert extra code (typically CSS or JavaScript, but could be anything) into specific Posts/Pages. The custom code can be inserted anywhere the Post appears, or only when viewing that Post alone (single view) Who says every one of your Posts has to have the same styling? Nobody, that’s who. Does every article in a magazine look exactly the same? No, not only because that would be boring but because each article is unique and should be designed as such. Having complete stylistic and functional control over every Post and Page of your site is very powerful and opens up some awesome design possibilities.

FeedBurner FeedSmith

The point of using FeedBurner is to get some statistics on how many people subscribe to your site. But what point are statistics unless they are accurate? This plugin will redirect anyone trying to access your WordPress feed directly to your FeedBurner feed address. Set-it-and-forget-it.

W3 Total Cache

Boosts the performance of your site (i.e., how fast your page loads) by combining a variety of techniques: file caching, database query caching, minifying/compressing/ combining files, CDN integration, and more.

WP-DBManager

There is nothing more important and vital to your WordPress-powered site than the mysterious database that lives on your server. If your entire server was destroyed, but you had a recent backup of your database, you would be OK. WP-DBManager makes sure you’re covered with robust database management from within the WordPress Admin area. WP-DBManager makes it easy to automatically backup, optimize, repair, and even send backups via email.

Posts Per Page

There is only one setting in WordPress to display how many Posts to show on a page (located under Settings > Reading). But what if it made sense to display only one post at a time on your blog’s homepage? That would mean that your search page would also display only one post, which is dumb. The Posts Per Page plugin allows you more fine-grained control over how many Posts are displayed for each type of page, including search pages, category pages, archive pages, and everything else.

Post Editor Buttons

There is a user-setting for turning off the visual editor. When you do that, instead of the rich-text editor you see when creating posts, you just get a few buttons and see the raw HTML in the content box. The full control over formatting that this editing mode provides is nice, but the buttons you get are fairly limited. The good news is that the Post Editor Buttons plugin allows you to create your own buttons on the fly, which potentially could be useful for any type of site. Below, we see a number of custom buttons added: “h3”, “h4”, as well as buttons such as “html”, which wraps the selected text in their respective tags.

WordPress SEO by Yoast

The only SEO plugin you need to further optimize WordPress for the search engines. One stop does it all: on-page analysis, feed optimization, breadcrumb navigation, and easy import from other SEO plugins like All in One SEO and Headpsace2 SEO. It’s MultiSite-compatible, has tons of extra features, and even takes care of your XML sitemaps! Visit the plugin page at the Codex for full details.

Google XML Sitemaps

If you’re not using the WordPress SEO plugin to create your XML sitemaps, this plugin will do the job beautifully. Simply install, configure, and presto! — instant XML-sitemap functionality for your entire site. With the Google XML Sitemaps plugin, your sitemap will be Google-compliant, and updated every time you edit or create a post. Then, whenever your sitemap is updated, major search engines like Google, Bing, and Yahoo are instantly notified. Best of all, everything happens quietly and automatically behind the scenes, so you can focus on creating fresh content for your visitors.

Clean Notifications

The default comment notification email from WordPress is kind of fugly. It’s plain text, and contains a whole bunch of links. Thankfully, the Clean Notifications plugin utilizes some very basic HTML to help the emails look much more readable and user-friendly (see screenshot at right).

Subscribe To Comments

This plugin makes it easy to stay current with the conversation by clicking a checkbox next to the comment form. After checking the box and submitting a comment, you will receive an email whenever a new reply is posted on the thread. Best of all, you can unsubscribe at any time by clicking a link in any one of the email notifications.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment