search ]

Archives: Snippets | Page 18

Limit WordPress Search to Specific Post Types

Ever wondered how to limit search results to a specific Custom Post Type? It is simple. We have already seen how to completely disable WordPress search by modifying functions.php. Now we will do something similar to filter our search results.

Add the following code to your functions.php file:

function sv_search_filter($query) {
 
    if ($query->is_search && !is_admin() ) {
        $query->set('post_type',array('post','page'));
    }
 
return $query;
}
 
add_filter('pre_get_posts','sv_search_filter');

Note this line:

$query->set('post_type',array('post','page'));

You can filter search results by changing the values in that array. Search results will now show only pages and posts, but you can change this array to include any post type you want.

Show Only Free Shipping in WooCommerce Cart and Checkout

By default, WooCommerce displays all shipping options on the cart and checkout pages. If you want to show only the free shipping option on these pages, add the following code to functions.php:

/**
 * Hide shipping rates when free shipping is available.
 * Updated to support WooCommerce 2.6 Shipping Zones.
 *
 * @param array $rates Array of rates found for the package.
 * @return array
 * @link https://docs.woocommerce.com/document/hide-other-shipping-methods-when-free-shipping-is-available/
 */
function prefix_hide_shipping_when_free_is_available( $rates ) {
	$free = array();
	foreach ( $rates as $rate_id => $rate ) {
		if ( 'free_shipping' === $rate->method_id ) {
			$free[ $rate_id ] = $rate;
			break;
		}
	}
	return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'prefix_hide_shipping_when_free_is_available', 100 );

Multiple Excerpt Lengths in WordPress

You may or may not know that you can change or set the excerpt length in WordPress using the following filter:

function sv_excerpt_length( $length ) {
    return 15;
}
add_filter( 'excerpt_length', 'sv_excerpt_length' );

But that sets one excerpt length every time you use the the_excerpt function. What if you want different excerpt lengths in different places in your theme? In that case, you can use the following code 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;
}

Then you can set the excerpt length in your theme like this:

<?php echo excerpt(25); ?>

Remove Archive/Tag/Author Prefix from Archive Title

You can use the following filter for this:

add_filter( 'get_the_archive_title', function ($title) {
    if ( is_category() ) {
        $title = single_cat_title( '', false );
    } elseif ( is_tag() ) {
        $title = single_tag_title( '', false );
    } elseif ( is_author() ) {
        $title = '<span class="vcard">' . get_the_author() . '</span>' ;
    } elseif ( is_tax() ) { //for custom post types
        $title = sprintf( __( '%1$s' ), single_term_title( '', false ) );
    } elseif (is_post_type_archive()) {
        $title = post_type_archive_title( '', false );
    }
    return $title;
});

This uses the get_the_archive_title filter. Learn more in WordPress Hooks Explained.

Check if a Post Has Embedded Content

The following snippet lets you check whether a specific post has embedded content. It works inside the loop using the post ID. Alternatively, you can pass any ID to check if that post contains embedded content.

<?php

function has_embed( $post_id = false ) {
	if( !$post_id ) $post_id = get_the_ID();
	else $post_id = absint( $post_id );
	if( !$post_id ) return false;

	$post_meta = get_post_custom_keys( $post_id );
	$post_meta = array_map( 'trim' , $post_meta );

	foreach( $post_meta as $meta ) {
		if( '_oembed' != substr( $meta , 0 , 7 ) )
			continue;
		return true;
	}
	return false;
}

Usage:

if( has_embed() ) {
   // do whatever
}

For more on embedded content, see Improving Loading Time of Embedded Videos.

Pre-populating Post Types with Default Content

The following snippet lets you add default content automatically to every new post of a given post type. Add to functions.php:

<?php
////////////////////////////////////////////////////////////////////////////////////
// This auto populates post types and posts.
///////////////////////////////////////////////////////////////////////////////////


function my_editor_content( $content ) {

	global $post_type;

	switch( $post_type ) {
		case 'your_post_type_here': //auto populate
			$content = 'The content you want to pre-populate the post type with.';
			break;
	}

	return $content;
}
add_filter( 'default_content', 'my_editor_content' );

For more on custom post types, see How to Create Custom Post Types.

Style the ACF Admin Interface

Here is how to add CSS to the ACF admin interface. In this case, we made Repeater Fields have clearer separation. Several other changes were made to improve the interface readability:

Note: Remove the opening PHP tag from the code…

<?php
function my_acf_admin_head() {t?>
    <style type="text/css">

        .acf-flexible-content .layout .acf-fc-layout-handle {
            background-color: #202428;
            color: #eee;
        }

        .acf-repeater.-row > table > tbody > tr > td,
        .acf-repeater.-block > table > tbody > tr > td {
            border-top: 2px solid #202428;
        }

        .acf-repeater .acf-row-handle {
            vertical-align: top !important;
            padding-top: 16px;
        }

        .acf-repeater .acf-row-handle span {
            font-size: 20px;
            font-weight: bold;
            color: #202428;
        }

        .imageUpload img {
            width: 75px;
        }

        .acf-repeater .acf-row-handle .acf-icon.-minus {
            top: 30px;
        }

    </style>
t<?php
}

add_action( 'acf/input/admin_head', 'my_acf_admin_head' );

And here is the result for the Repeater. Notice the separator line?

Making the Repeater have clearer styling

Add CSS to WooCommerce Emails

To change the styling of emails that WooCommerce sends, you can add inline CSS using the woocommerce_email_header hook. Add the following code to your functions.php file:

<?php
/**
 * WooCommerce
 * Add inline CSS to emails sent out
 */
function sv_add_css_to_woo_email() {
    echo '<style type="text/css">
             h1 {
                 text-align: center !important;
                 color: #DDD;
             }
         </style></pre>'; 
}
add_action( 'woocommerce_email_header', 'sv_add_css_to_woo_email' );

For more WooCommerce email customization, see Mastering WooCommerce Hooks.

Change the Breadcrumb Delimiter in WooCommerce

To change the breadcrumb delimiter in WooCommerce, use the following filter:

function in_woocommerce_breadcrumb_defaults($args){
    $args['delimiter']   = '&nbsp;&#124;&nbsp;';
    return $args;
}
add_filter('woocommerce_breadcrumb_defaults','in_woocommerce_breadcrumb_defaults');

In this case we replaced the slash with a vertical bar. Here are all the values you can change with this filter:

array(
   'delimiter'   => '&nbsp;&#47;&nbsp;',
   'wrap_before' => '<nav class="woocommerce-breadcrumb">',
   'wrap_after'  => '</nav>',
   'before'      => '',
   'after'       => '',
   'home'        => _x( 'Home', 'breadcrumb', 'woocommerce' ),
)
Savvy WordPress Development official logo