- Get_template_part() output via Shortcode
- Standard WordPress Loop
- Displaying posts using Bootstrap 3 or 4
- Connecting styles and scripts in WordPress
- Connecting directly in <head> of the page
- Connecting in functions.php
- Registration and display of the menu in theme
- How to limit the number of characters in a function the_excerpt()
- Adding a panel with options using Advanced Custom Fields PRO
- Disable all WordPress updates
- How to register Custom post type
Snippet is a short piece of code that performs a specific function and can be reused in development.
Regarding CMS WordPress – the use of snippets will significantly speed up the creation of a website and help the wordpress-developer “not reinvent the wheel” in solving their problems.
In this article, we will look at the best, in our opinion, snippets for CMS WordPress, which are used by the developers of our company.
Get_template_part() output via Shortcode
Very often there are situations when you need to insert a piece of code into the WordPress editor. For example, you wrote a paragraph of text, after which you want to put a manually written slider.
How to insert the created slider into the finished code so as not to break anything? Of course – using a shortcode. The WordPress repository provides a large number of different sliders that can be embedded into your code using a construction like [slick-slider]. But what if we want to use our own custom slider, which we have been writing for so long? Everything is very simple.
We register a new shortcode in functions.php that will return us a template with our slider or any other code fragment you need. To do this, we use the function – get_template_part(), then get the contents of the current buffer and clean it up with the function – ob_get_clean. Now in the editor we can call the short code – [slider], which in turn will pull up the slider-part.php template. Don’t forget that we don’t use get_header() and get_footer() in this file!
function slider-shortcode( $attr ) { ob_start(); get_template_part( 'slider-part' ); return ob_get_clean(); } add_shortcode( 'slider', 'slider-shortcode' );к содержанию ↑
Standard WordPress Loop
The backbone of WordPress website development is a standard loop that displays all posts. This is a frequently used snippet, it takes a long time to write and you have to look at the code often in order to understand how it looks. Here he is
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php the_title(); ?> <?php endwhile; else : ?> <p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?>
Loop that outputs posts with custom post type
You have created your own type of records, now you need to display these records somehow. This is where wp_query{} comes to the rescue. This is a PHP class that receives records from the database according to the parameters that we give it. We specify the parameters in the $args array.
<?php $args=array( 'post_type' => 'artist', 'post_status' => 'publish', 'posts_per_page' => -1, ); $my_query = null; $my_query = new WP_Query($args);if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); the_title(); endwhile;} wp_reset_query(); ?>к содержанию ↑
Displaying posts using Bootstrap 3 or 4
Probably the most frequently asked question on stackoverflow. We all know that in bootstrap 3-4 – columns need to be split in rows – <div class=”row”></div>. The problem is that the standard WordPress loop will display all the posts that are in the database and that’s it. We need to somehow break this cycle so that every 3 posts (imagine that we have a grid of 3 columns) are split side by side (row). For this we use wp_query. And now the most magical and simple thing – we just wrap every 4 elements of the loop in <div class=”row”></div> using a simple construction:
if($i % 4 == 0) { ?> <div class="row"> <?php } ?>
Now we need to close div. We close with this construction:
<?php $i++; if($i != 0 && $i % 4 == 0) { ?> </div><!--/.row--> <div class="clearfix"></div> <?php } ?>
Add <div class=”clearfix”></div> so that Bootstrap 3, which is still on float, breaks columns in rows.
Ready code:
<?php $args=array( 'post_type' => 'portfolio', 'post_status' => 'publish', 'posts_per_page' => -1, ); $my_query = null; $my_query = new WP_Query($args);if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); if($i % 4 == 0) { ?> <div class="row"> <?php } ?> <div class="col-md-3"> <?php the_title(); ?> </div> <?php $i++; if($i != 0 && $i % 4 == 0) { ?> </div><!--/.row--> <div class="clearfix"></div> <?php } endwhile; wp_reset_query(); }?>к содержанию ↑
Connecting styles and scripts in WordPress
There are several options for including scripts and styles in a theme. Let’s consider the most popular ones:
Connecting directly in <head> of the page
I think that almost every developer who included style files wanted to immediately get into header.php and connect the style using the standard construction:
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/styles.css">
This option will work, but it is wrong to do so, since some caching plugins such as WP Total Cache will not be able to see and process the styles connected in this way.
Connecting in functions.php
Let’s consider the correct option, which we recommend using in development. We will use a function that is included in the functions.php file:
function name(){ wp_enqueue_style( 'foundation-min-css', get_template_directory_uri() . '/css/style.css', array(), '1.0.0', 'all'); wp_enqueue_script('app-js', get_template_directory_uri() . '/js/app.js', array(), '1.0.0', true); } add_action( 'wp_enqueue_scripts', 'name' );
wp_enqueue_style – function that registers the stylesheet
wp_enqueue_script – function that registers js files
You can read more about these functions in official documentation.
After registering the styles, we need to call our function. For this we use – add_action – wp_enqueue_scripts.
к содержанию ↑Registration and display of the menu in theme
One of the most frequently asked questions in Google searches from wordpress developers. How do I display the “menu”? How do I register it? Everything is very simple. First, let’s add a function that will create the menu we need and display it in the WordPress admin area. In the function, we pass an array with the number of “menus” that we need. In the example we will create one menu – topmenu
register_nav_menus(array('top'=>'topmenu'));
We registered the “menu”, added several items of this “menu” to the admin panel. Next, you need to bring it out somewhere.
In the subject – we insert the following code using the wp_nav_menu function. We pass to the array – the menu that needs to be displayed + wrap it in the classes and tags we need.
<?php wp_nav_menu( array ( 'menu' => 'topmenu', 'items_wrap' => '<ul class="mobile_menu text-left main_menu" data-dropdown-menu>%3$s</ul>' )); ?>
к содержанию ↑
How to limit the number of characters in a function the_excerpt()
Function the_excerpt() displays all the content that we will put in the short content of the post. Very often you need to display all its content in the post itself, and for example, on the category page, where we have a grid with posts, display only the first 20 characters, hide the rest under dots (…)
To do this, create a function in functions.php
function excerpt($limit) { $excerpt = explode(' ', get_the_excerpt(), $limit); if (count($excerpt)>=$limit) { array_pop($excerpt); $excerpt = implode(" ",$excerpt).'...'; } else { $excerpt = implode(" ",$excerpt); } $excerpt = preg_replace('`[[^]]*]`','',$excerpt); return $excerpt; }
We transfer our – get_the_excerpt() and check if it matches the specified number of characters, add 3 dots and return a variable with our content. Now in the place we need – we call the function and pass into it the number of characters that we need.
<?php echo excerpt(20) ?>к содержанию ↑
Adding a panel with options using Advanced Custom Fields PRO
Very often we have to add the ability for the client to change the content that is used on all pages of the site. For example: logo, phone numbers, e-mail, etc.
We can use standard WordPress meta fields for this, but I find they are extremely awkward, with an unattractive design. For this, it is best to use the plugin “ACF PRO” (you can read more about this plugin in our article «Best WordPress plugins»).
First, we need to register our options panel in functions.php.
if( function_exists('acf_add_options_page') ) { acf_add_options_page(array( 'page_title' => 'Theme Settings', 'menu_title' => 'Theme Settings', 'menu_slug' => 'theme-general-settings', )); }
Specify the page title, menu title, slug in the array.
After that, in the ACF plugin panel, add our group of fields. Below on the page, we indicate that it belongs to our options panel – theme settings.
In the admin panel, we will have a menu item that is responsible for our panel with settings. We fill in all the data. In our case, this is a logo and a phone.
Next, we need to display in the subject, in the place we need, the fields that we have created. This is done simply:
<?php echo get_field(‘logo’, ‘options’) ?> – will return us the url to the image
<?php echo get_field(‘tel-1’, ‘options’) ?> – will return us the text, in this case the phone number that we provided on the options page.
к содержанию ↑Disable all WordPress updates
There are times when you need to protect the client from unnecessary actions in the administrative panel. If the client has full access to the admin panel and to all of its sections, there is a danger that a person not knowing the specifics of the CMS WordPress updates all plugins and the core itself. In this case, conflicts between new versions of plugins and the WP core itself may arise. To avoid such problems, you need to turn off updates. This is done quite simply – we add several filters to the functions.php file
// WordPress updates add_filter('pre_site_transient_update_core',create_function('$a', "return null;")); wp_clear_scheduled_hook('wp_version_check'); // plugins updates remove_action( 'load-update-core.php', 'wp_update_plugins' ); add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) );к содержанию ↑
How to register Custom post type
Above, we looked at how to display posts with a custom post type. We will now look at how to create a custom post type to display in the admin panel.
The problem is this: in WordPress there are Posts and Pages – usually posts are used for News or Blogs. Pages – for static pages. Let’s say we need to create a custom post type – Products. To do this, go to the functions.php file and register our custom post
// Register Custom Post Type function custom_post_type() { $labels = array( 'name' => _x( 'Post Types', 'Товары', 'text_domain' ), 'singular_name' => _x( 'Post Type', 'Товар', 'text_domain' ), 'menu_name' => __( 'Товары', 'text_domain' ), 'name_admin_bar' => __( 'Товары', 'text_domain' ), 'archives' => __( 'Item Archives', 'text_domain' ), 'attributes' => __( 'Item Attributes', 'text_domain' ), 'parent_item_colon' => __( 'Parent Item:', 'text_domain' ), 'all_items' => __( 'All Items', 'text_domain' ), 'add_new_item' => __( 'Add New Item', 'text_domain' ), 'add_new' => __( 'Add New', 'text_domain' ), 'new_item' => __( 'New Item', 'text_domain' ), 'edit_item' => __( 'Edit Item', 'text_domain' ), 'update_item' => __( 'Update Item', 'text_domain' ), 'view_item' => __( 'View Item', 'text_domain' ), 'view_items' => __( 'View Items', 'text_domain' ), 'search_items' => __( 'Search Item', 'text_domain' ), 'not_found' => __( 'Not found', 'text_domain' ), 'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ), 'featured_image' => __( 'Featured Image', 'text_domain' ), 'set_featured_image' => __( 'Set featured image', 'text_domain' ), ); $args = array( 'label' => __( 'Post Type', 'text_domain' ), 'description' => __( 'Post Type Description', 'text_domain' ), 'labels' => $labels, 'supports' => false, 'taxonomies' => array( 'category', 'post_tag' ), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'page', ); register_post_type( 'post_type', $args ); } add_action( 'init', 'custom_post_type', 0 );
Don’t be intimidated by the sheer number of options. Basically, these are translations and headings of menu items such as “Add Product”, “All Products”, etc.
Description of each of the array parameters – you can find in the official WordPress documentation
https://codex.wordpress.org/Function_Reference/register_post_type
Take a close look at the array parameters $args. After registering a custom type, you will see a “Products” section in your menu.
We will be grateful for your comments and questions, it will inspire us to write new interesting articles!