WordPress Code Snippets
Once you have a Wordpress site setup and you have access to the functions.php
this is where the fun starts. You can start dropping snippets of code into the functions file, give your website a refresh and you should see your new functions taking place. However, be carful as php errors are unforgiving. So you really want to be testing out this code locally first.
Below is some snippets ive collected
Hide acf fields on production
Why do this?
- Fields wont get overwritten when deploying from local or staging
- Stop clients from deleting acf fields in production
How to hide
- add to
functions.php
- update protected urls
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
add_filter(
'acf/settings/show_admin',
function () {
// Get the current site url.
$site_url = get_bloginfo( 'url' );
// Define an array of protected site urls.
$protected_urls = array(
'https://staging.cloud',
'https://live.com.au',
);
// If the current site URL is in the array of protected URLs, return FALSE
// to hide the menu.
return ! in_array( $site_url, $protected_urls );
}
);
more info
Custom Excerpt Length
Change the length of the post excerpt length
1
2
3
4
function custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
Custom Excerpt More
Change the excerpt display link based on what post type is being viewed
1
2
3
4
5
6
7
8
function new_excerpt_more( $more ) {
if ('testimonials' == get_post_type()) {
return ' <br /><a class = "more" href="'. get_permalink(isset($post->ID)) . '"> View</a>';
} else {
return ' <br /><a class = "more" href="'. get_permalink(isset($post->ID)) . '"> Read More</a>';
}
}
add_filter('excerpt_more', 'new_excerpt_more');
Put WordPress into maintenance mode
One of the best features of Wordpress is how customisable it is. There are so many plugins that allow you to customise your Wordpress site.
However, Its much nicer to be able to do stuff in Wordpress without using a plugin.
One such task is putting it into maintenance mode. Granted, it’s not something you have to do often. But when you do you can use a snippet rather then a plugin.
Activate WordPress Maintenance Mode
Here we are using an action to put WordPress into maintenance mode. First the script checks to see if the user is not logged in. Add to functions.php
1
2
3
4
5
6
7
// Activate WordPress Maintenance Mode
function wp_maintenance_mode() {
if (!current_user_can('edit_themes') || !is_user_logged_in()) {
wp_die('<h1>Under Maintenance</h1><br />Website under planned maintenance. Please check back later.');
}
}
add_action('get_header', 'wp_maintenance_mode');
Wordpress query post loops
Queries that will return some posts according to the configuration of your query
Page basic template with loop
1
2
3
4
5
6
7
8
9
10
11
12
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2><?php the_title() ;?></h2>
<?php the_post_thumbnail(); ?>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, no posts to list</p>
<?php endif; ?>
Advanced Loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php if(is_category('featured')): ?>class="featured-post"<?php endif; ?>>
<h1><?php the_title() ;?></h1>
<p>
Published on <?php the_time('M j, Y'); ?>
by <?php the_category(', '); ?>
in <?php the_category(', '); ?>
</p>
<?php the_content(); ?>
<?php comment_form(); ?>
<div class="prev-next-links">
<ul>
<li><?php next_post_link(); ?></li>
<li><?php previous_post_link(); ?></li>
</ul>
</div>
</article>
<?php endwhile; else: ?>
<p>Sorry, this post does not exist</p>
<?php endif; ?>
loop using query posts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php query_posts('showposts=1&post_type=post'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h1><?php the_title() ;?></h1>
<?php the_post_thumbnail(); ?>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, there are no posts to display</p>
<?php endif; ?>
<hr>
<?php rewind_posts(); ?>
<?php query_posts('showposts=3&offset=1&post_type=post'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2><?php the_title() ;?></h2>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, there are no posts to display</p>
<?php endif; ?>
loop using wp query
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
$args = array(
'pagename' => 'about-us'
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h1><?php the_title() ;?></h1>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, there are no posts to display</p>
<?php endif; ?>
more complex example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
$args = array(
'author_name' => 'zgordon',
'orderby' => 'title',
'post_type' => 'workshops'
'year' => 2012
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h1><?php the_title() ;?></h1>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, there are no posts to display</p>
<?php endif; ?>
Enqueue styles in the footer
Used for critical css
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function my_deregister_styles() {
wp_deregister_style('parent');
wp_deregister_style( 'divi-style' );
wp_deregister_style( 'tt-widget-css' );
}
add_action('wp_enqueue_scripts', 'my_deregister_styles', 100);
//load style on footer
function pxs_add_footer_styles() {
$parent_style = 'parent-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array('parent-style') );
wp_enqueue_style( 'tt-widget-css', get_stylesheet_directory_uri() . '/wp-content/plugins/ticket-tailor/tt-widget.css' );
};
add_action( 'get_footer', 'pxs_add_footer_styles' );
Move Yoast to bottom
1
2
3
4
5
function yoasttobottom() {
return 'low';
}
add_filter( 'wpseo_metabox_prio', 'yoasttobottom');
redirect user on failed login
1
2
3
4
5
6
7
8
9
10
11
add_action( 'wp_login_failed', 'my_callback' );
function my_callback() {
if (! is_user_logged_in()) {
wp_redirect( 'https://example.com.au', 301 );
exit();
} else {
wp_redirect( 'https://example.com.au/login/', 301 );
exit();
}
}
style header info
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
Theme Name: Twenty Seventeen
Theme URI: https://wordpress.org/themes/twentyseventeen/
Author: the WordPress team
Author URI: https://wordpress.org/
Description: Twenty Seventeen brings your site to life with immersive featured images and subtle animations. With a focus on business sites, it features multiple sections on the front page as well as widgets, navigation and social menus, a logo, and more. Personalize its asymmetrical grid with a custom color scheme and showcase your multimedia content with post formats. Our default theme for 2017 works great in many languages, for any abilities, and on any device.
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: twentyseventeen
Tags: one-column, two-columns, right-sidebar, flexible-header, accessibility-ready, custom-colors, custom-header, custom-menu, custom-logo, editor-style, featured-images, footer-widgets, post-formats, rtl-language-support, sticky-post, theme-options, threaded-comments, translation-ready
This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned with others.
*/
wp_schedule_event
secure area
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
/* include via page template
Pipe all knowledge base users through the one page template to easily test if user is logged in or not.
*/
?>
<section class = "secure_area">
<div class = "container">
<div class = "secure_area__wrapper">
<?php if (is_user_logged_in()) { ?>
<h2>Search</h2>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; else: ?>
<?php get_template_part('notfound');
endif; ?>
<?php } else { ?>
<?php echo '<div class = "notification"><h2 class = "text">You will need to <a href = "/wp/wp-login.php?action=register">Register</a> or <a href = "/login">Login</a> to view the secure area</h2></div>'; ?>
<?php } ?>
</div>
</div>
</section>
date counter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
function DateCounter($atts){
$startDate = $atts["startdate"];
$endDate = strtolower($atts["enddate"]);
switch (strtolower($atts["format"])) {
case "year":
case "years":
$startDate = new DateTime($startDate);
$endDate = new DateTime($endDate);
$difference = $endDate->diff($startDate);
$result = $difference->y;
break;
case "month":
case "months":
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
$min_date = min($startDate, $endDate);
$max_date = max($startDate, $endDate);
$i = 0;
while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
$i++;
}
$result = $i;
break;
case "day":
case "days":
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
$difference = $endDate - $startDate;
$result = floor($difference / (60*60*24));
break;
case "currentyear":
$result = date("Y");
break;
case "currentmonth":
$result = date("m");
break;
case "currentday":
$result = date("d");
break;
}
return $result;
}
add_shortcode( 'DateCounter', 'DateCounter' );
?>
featured image
1
2
3
4
5
<?php if ( has_post_thumbnail()) {
$image_src = wp_get_attachment_image_src( get_post_thumbnail_id(), $pxs_img_size );
echo '<img src="' . $image_src[0] . '" width="100%" />'; ?>
<?php }
Enable Gutenberg for Custom Post Type
If you want to use Gutenberg for editing your custom post types. And why wouldn’t you it’s amazing and easily the best option for WordPress content editing. Then you need to edit and add this piece of code into your functions.php
to enable a Gutenberg. In this example we are initiating a custom post type called events
. You’ll want to edit events to suit your custom post type.
Prerequisites
- An active WordPress install, either local or on a remote server
- The ability to edit the
functions.php
The below cpt snippet utilises the 'show_in_rest' => true
and 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
which is are the key parts to enabling Gutenberg in custom post types.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function pxs_events_init() {
$labels = array(
'name' => _x( 'events', 'Post type general name', 'textdomain' ),
'singular_name' => _x( 'events', 'Post type singular name', 'textdomain' ),
'menu_name' => _x( 'events', 'Admin Menu text', 'textdomain' ),
'name_admin_bar' => _x( 'events', 'Add New on Toolbar', 'textdomain' ),
'add_new' => __( 'Add New', 'textdomain' ),
'add_new_item' => __( 'Add New events', 'textdomain' ),
'new_item' => __( 'New events', 'textdomain' ),
'edit_item' => __( 'Edit events', 'textdomain' ),
'view_item' => __( 'View events', 'textdomain' ),
'all_items' => __( 'All events', 'textdomain' ),
'search_items' => __( 'Search events', 'textdomain' ),
'parent_item_colon' => __( 'Parent events:', 'textdomain' ),
'not_found' => __( 'No s found.', 'textdomain' ),
'not_found_in_trash' => __( 'No s found in Trash.', 'textdomain' ),
'featured_image' => _x( 'events Cover Image', 'Overrides the “Featured Image” phrase for this post type. Added in 4.3', 'textdomain' ),
'set_featured_image' => _x( 'Set cover image', 'Overrides the “Set featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
'remove_featured_image' => _x( 'Remove cover image', 'Overrides the “Remove featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
'use_featured_image' => _x( 'Use as cover image', 'Overrides the “Use as featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
'archives' => _x( 'events archives', 'The post type archive label used in nav menus. Default “Post Archives”. Added in 4.4', 'textdomain' ),
'insert_into_item' => _x( 'Insert into ', 'Overrides the “Insert into post”/”Insert into page” phrase (used when inserting media into a post). Added in 4.4', 'textdomain' ),
'uploaded_to_this_item' => _x( 'Uploaded to this ', 'Overrides the “Uploaded to this post”/”Uploaded to this page” phrase (used when viewing media attached to a post). Added in 4.4', 'textdomain' ),
'filter_items_list' => _x( 'Filter s list', 'Screen reader text for the filter links heading on the post type listing screen. Default “Filter posts list”/”Filter pages list”. Added in 4.4', 'textdomain' ),
'items_list_navigation' => _x( 'events list navigation', 'Screen reader text for the pagination heading on the post type listing screen. Default “Posts list navigation”/”Pages list navigation”. Added in 4.4', 'textdomain' ),
'items_list' => _x( 'events list', 'Screen reader text for the items list heading on the post type listing screen. Default “Posts list”/”Pages list”. Added in 4.4', 'textdomain' ),
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'menu_icon' => 'dashicons-tide',
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => '' ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'show_in_rest' => true,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
);
register_post_type( 'events', $args );
}
add_action( 'init', 'pxs_events_init' );