Code Snippets Archive - Bill Erickson https://www.billerickson.net/code/ WordPress Design and Development Thu, 03 Feb 2022 22:37:10 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://www.billerickson.net/wp-content/uploads/2018/11/cropped-favicon-150x150.png Code Snippets Archive - Bill Erickson https://www.billerickson.net/code/ 32 32 Logo dimensions as CSS variable https://www.billerickson.net/code/logo-dimensions-as-css-variable/ Thu, 03 Feb 2022 22:37:10 +0000 https://www.billerickson.net/?post_type=code&p=8628 The post Logo dimensions as CSS variable appeared first on Bill Erickson.

]]>
$logo = shortcode_parse_atts( cwp_icon( [ 'icon' => 'logo', 'group' => 'logo', 'size' => false, 'force' => true ] ) ); if ( ! empty( $logo['viewbox'] ) ) { $dimensions = explode( ' ', $logo['viewbox'] ); $style = 'body { --cwp-logo-width: ' . $dimensions[2] . 'px; --cwp-logo-height: ' . $dimensions[3] . 'px;}'; wp_add_inline_style( 'theme-style', $style ); }

The post Logo dimensions as CSS variable appeared first on Bill Erickson.

]]>
Disable loading=”lazy” on images in first block https://www.billerickson.net/code/disable-loadinglazy-on-images-in-first-block/ Thu, 14 Oct 2021 15:03:38 +0000 https://www.billerickson.net/?post_type=code&p=8622 The post Disable loading=”lazy” on images in first block appeared first on Bill Erickson.

]]>
add_filter( 'pre_render_block', function( $pre_render ) { global $cwp_block; if ( empty( $cwp_block ) ) { $cwp_block = 1; } else { $cwp_block++; } return $pre_render; } ); add_filter( 'wp_lazy_loading_enabled', function( $default ) { global $cwp_block; if ( 1 === $cwp_block ) { $default = false; } return $default; } );

The post Disable loading=”lazy” on images in first block appeared first on Bill Erickson.

]]>
Set max srcset image to 2x https://www.billerickson.net/code/set-max-srcset-image-to-2x/ Thu, 07 Jan 2021 19:06:01 +0000 https://www.billerickson.net/?post_type=code&p=8604 The post Set max srcset image to 2x appeared first on Bill Erickson.

]]>
/** * Max srcset image size */ function be_max_srcset_image_size( $max_width, $sizes ) { return 2 * $sizes[0]; } add_filter( 'max_srcset_image_width', 'be_max_srcset_image_size', 10, 2 );

The post Set max srcset image to 2x appeared first on Bill Erickson.

]]>
Author archive link pointed to about page https://www.billerickson.net/code/author-archive-link-pointed-to-about-page/ Thu, 03 Sep 2020 15:31:05 +0000 https://www.billerickson.net/?post_type=code&p=8406 The author name at the top of a post typically points to that author’s archive page (example). You can use the author_link¬†filter to point it to any URL you’d like.…

The post Author archive link pointed to about page appeared first on Bill Erickson.

]]>
The author name at the top of a post typically points to that author’s archive page (example). You can use the author_link¬†filter to point it to any URL you’d like.

In this case, I have every author link pointed to the site’s /about/ page. You could use the $author_id parameter to use a different URL based on the user (ex: linking to that user’s Website field from their profile).

// Author URL goes to about page
add_filter( 'author_link', function( $link, $author_id ) {
	return trailingslashit( home_url( 'about' ) );
}, 10, 2 );

The post Author archive link pointed to about page appeared first on Bill Erickson.

]]>
WP Recipe Maker – query for posts with videos in recipe card https://www.billerickson.net/code/wprm-video-post-query/ Mon, 03 Aug 2020 15:32:15 +0000 https://www.billerickson.net/?post_type=code&p=8393 This first runs a query for recipes that have videos, then loops through those recipes and adds the “parent post id” to an array. This is the post to which…

The post WP Recipe Maker – query for posts with videos in recipe card appeared first on Bill Erickson.

]]>
This first runs a query for recipes that have videos, then loops through those recipes and adds the “parent post id” to an array. This is the post to which the recipe was attached. We then query for those posts.

$recipes = new WP_Query( [
	'post_type' => 'wprm_recipe',
	'posts_per_page' => 8,
	'fields' => 'ids',
	'update_post_term_cache' => false,
	'ignore_sticky_posts' => true,
	'no_found_rows' => true,
	'meta_query' => [
		[
			'key' => 'wprm_video_embed',
			'value' => '',
			'compare' => '!=',
		]
	]
]);

if( empty( $recipes->posts ) )
	return;

$post_ids = [];
foreach( $recipes->posts as $recipe_id ) {
	$post_id = get_post_meta( $recipe_id, 'wprm_parent_post_id', true );
	if( !empty( $post_id ) && 'post' === get_post_type( $post_id ) )
		$post_ids[] = intval( $post_id );
}

$posts = new WP_Query( [
	'post__in'	=> $post_ids,
	'orderby'	=> 'post__in',
]);

The post WP Recipe Maker – query for posts with videos in recipe card appeared first on Bill Erickson.

]]>
Track PWA install in Google Analytics https://www.billerickson.net/code/track-pwa-install-in-google-analytics/ Fri, 12 Jun 2020 22:25:18 +0000 https://www.billerickson.net/?post_type=code&p=8354 The post Track PWA install in Google Analytics appeared first on Bill Erickson.

]]>
window.addEventListener('appinstalled', (event) => { if ( 'function' === typeof ga ) { // Default GA. ga( 'send', 'event', 'pwa', 'install ); } else if ( 'function' === typeof __gaTracker ) { // MonsterInsights. __gaTracker( 'send', 'event', 'pwa', 'install' ); } });

The post Track PWA install in Google Analytics appeared first on Bill Erickson.

]]>
WPForms Order Number https://www.billerickson.net/code/wpforms-order-number/ Thu, 04 Jun 2020 18:32:50 +0000 https://www.billerickson.net/?post_type=code&p=8351 Generate sequential order numbers for WPForms submissions. Add a hidden field to your form named “Order Number” and add a CSS class of order-number. When the form is submitted, the…

The post WPForms Order Number appeared first on Bill Erickson.

]]>
Generate sequential order numbers for WPForms submissions.

Add a hidden field to your form named “Order Number” and add a CSS class of order-number. When the form is submitted, the following code will update that field to have a sequential order number.

It stores the order number as a site-option and increments the number on successful form submission. It creates a separate option for each form so you can have multiple order forms with their own sequential numbering.

If you want a single sequential sequence used for all forms, set $use_single_sequence = true;.

I’m formatting the order number to have eight digits (ex: 00000001). You can change the number of digits by changing the “8” in %08d at the end.


/**
 * WPForms, Sequential Order Number
 * @author Bill Erickson
 * @link https://www.billerickson.net/code/wpforms-sequential-order-number
 */
function be_wpforms_order_number( $fields, $entry, $form_data ) {
	$use_single_sequence = false;
	$order_field_id = false;

	foreach( $form_data['fields'] as $field ) {
		if( empty( $field['css'] ) )
			continue;

		$classes = explode( ' ', $field['css'] );
		if( in_array( 'order-number', $classes ) )
			$order_field_id = $field['id'];
	}
	if( empty( $order_field_id ) )
		return $fields;

	$option = $use_single_sequence ? 'be_wpforms_order' : 'be_wpforms_' . $form_data['id'] . '_order';
	$order = intval( get_option( $option ) );
	$order++;
	update_option( $option, $order );

	$fields[ $order_field_id ]['value'] = sprintf( '%08d', $order );
	return $fields;
}
add_filter( 'wpforms_process_filter', 'be_wpforms_order_number', 10, 3 );

The post WPForms Order Number appeared first on Bill Erickson.

]]>
Rename category taxonomy https://www.billerickson.net/code/rename-category-taxonomy/ Mon, 25 May 2020 19:09:17 +0000 https://www.billerickson.net/?post_type=code&p=8341 The post Rename category taxonomy appeared first on Bill Erickson.

]]>
/** * Rename Category to Theme * */ function be_rename_category_theme() { $singular_name = 'Theme'; $plural_name = 'Themes'; $labels = array( 'name' => $plural_name, 'menu_name' => $plural_name, 'singular_name' => $singular_name, 'search_items' => 'Search ' . $plural_name, 'popular_items' => 'Popular ' . $plural_name, 'all_items' => 'All ' . $plural_name, 'parent_item' => 'Parent ' . $singular_name, 'parent_item_colon' => 'Parent ' . $singular_name . ':', 'edit_item' => 'Edit ' . $singular_name, 'view_item' => 'View ' . $singular_name, 'update_item' => 'Update ' . $singular_name, 'add_new_item' => 'Add New ' . $singular_name, 'new_item_name' => 'New ' . $singular_name . ' Name', 'separate_items_with_commas' => 'Separate ' . $plural_name . ' with commas', 'add_or_remove_items' => 'Add or remove ' . $plural_name, 'back_to_items' => '← Back to ' . $plural_name, 'items_list_navigation' => $plural_name . ' list navigation', 'items_list' => $plural_name . ' list', ); global $wp_taxonomies; $wp_taxonomies['category']->labels = (object) array_merge( (array) $wp_taxonomies['category']->labels, $labels ); } add_action( 'init', 'be_rename_category_theme' );

The post Rename category taxonomy appeared first on Bill Erickson.

]]>
Automatic alt tags on images in WordPress https://www.billerickson.net/code/wordpress-image-automatic-alt-text/ Fri, 01 May 2020 18:12:59 +0000 https://www.billerickson.net/?post_type=code&p=8333 When you insert an image into a post, the HTML is “hardcoded” into the post content. You can edit the image’s alt text in the Media Library, but this will only…

The post Automatic alt tags on images in WordPress appeared first on Bill Erickson.

]]>
When you insert an image into a post, the HTML is “hardcoded” into the post content. You can edit the image’s alt text in the Media Library, but this will only include the alt text for future uses of the image. It won’t automatically update all of the past uses of that image in your older posts.

The code below fixes this. When a page loads, it finds all of the images that are missing alt text and looks to see if you’ve specified an alt text for it in the Media Library. If so, it updates the image before loading the page.

Install the plugin

Download this zip file, then go to Plugins > Add New > Upload to install and activate it.

Download Now

You can now go to your Media Library and update the alt text for every image. You won’t have to edit every post and update each instance of the image.

Note: this will only work for posts that are using the Gutenberg block editor. Even if you’re using the block editor now, it’s likely that most of your older content is still using the classic editor.

You can use Bulk Block Converter to convert all the posts using the Classic editor to the Block editor, but be careful. I’d run the tool first on a staging environment and go through your posts to make sure there were no issues with the conversion.

add_filter( 'render_block', function( $content, $block ) {
	if( 'core/image' !== $block['blockName'] )
		return $content;

	$alt = get_post_meta( $block['attrs']['id'], '_wp_attachment_image_alt', true );
	if( empty( $alt ) )
		return $content;

	// Empty alt
	if( false !== strpos( $content, 'alt=""' ) ) {
		$content = str_replace( 'alt=""', 'alt="' . $alt . '"', $content );

	// No alt
	} elseif( false === strpos( $content, 'alt="' ) ) {
		$content = str_replace( 'src="', 'alt="' . $alt . '" src="', $content );
	}

	return $content;
}, 10, 2 );

The post Automatic alt tags on images in WordPress appeared first on Bill Erickson.

]]>
wp cli, save-permalink https://www.billerickson.net/code/wp-cli-save-permalink/ Thu, 30 Apr 2020 15:21:09 +0000 https://www.billerickson.net/?post_type=code&p=8331 This custom wp cli script saves the original permalink as post meta for comparisons later after changing permalink structure. To run, type wp save-permalink. It will go through all posts…

The post wp cli, save-permalink appeared first on Bill Erickson.

]]>
This custom wp cli script saves the original permalink as post meta for comparisons later after changing permalink structure.

To run, type wp save-permalink. It will go through all posts and add a meta_key of be_original_permalink with the current permalink as the value.

While this specific functionality might not be useful to most, you can use this as a guide to creating your own custom wp cli scripts.

Any time I need to update a large number of posts, I use wp cli because it’s fast and won’t time out. It also lets me ensure the code only executes once.

<?php
//Check to make sure WP_CLI is running. This way our code isn't loaded on normal site visits.
if ( defined('WP_CLI') && WP_CLI ) {

	class BE_Save_Permalink extends WP_CLI_Command {

		public $step = 1;
		public $per_step = 100;
		public $post_count = 0;
		public $max_num_pages = 0;
		private $complete = false;

		public function __invoke( $args, $assoc_args ) {

			$args = array(
				'posts_per_page' => - 1,
				'post_type'      => 'post',
				'fields'         => 'ids',
			);
			$post_ids = new WP_Query( $args );
			$this->post_count = count( $post_ids->posts );

			// always round up.
			// 80 total posts / 100 posts per step = .8 -> round this up to one page
			// 120 total posts / 100 posts per step = 1.2 -> round this up to two pages
			$this->max_num_pages = ceil( $this->post_count / $this->per_step );

			wp_reset_postdata();
			WP_CLI::line( 'Found ' . $this->post_count . ' posts' );


			while( false === $this->complete ){
				$this->process_step();
			} // end while

		} // end function

		private function process_step(){

			// check to see if we've exceeded the pages
			if( $this->max_num_pages < $this->step ){
				$this->complete = true;
				WP_CLI::line( 'We have exceeded the number of pages. Ending.' );
				return;
			} // end if

			$args = array(
				'posts_per_page' => $this->per_step,
				'paged' => $this->step,
				'post_type' => 'post',
				'no_found_rows' => true,
				'update_post_term_cache' => false
			);
			$my_query = new WP_Query( $args );

			if( $my_query->have_posts() ):

				while ( $my_query->have_posts() ) : $my_query->the_post();
					update_post_meta( get_the_ID(), 'be_original_permalink', get_permalink() );


					// Leave this off if dealing with thousands of posts
					// WP_CLI::line( 'Updated post with ID  ' . get_the_ID() );

				endwhile;

				// increment our step
				WP_CLI::line( 'Completed Step #' . $this->step);
				$this->step++;

			else:
				WP_CLI::line( 'ERROR! Query returned no posts!' );
			endif;

			wp_reset_postdata();
		} // end function
	} // end class

	WP_CLI::add_command( 'save-permalink', 'BE_Save_Permalink', [
		'shortdesc'	=> 'Saves the original permalink as post meta for comparisons later after changing permalink structure',
	] );

}// end if

The post wp cli, save-permalink appeared first on Bill Erickson.

]]>