Category Archives: WordPress

Preload styles

In functions.php

// set these styles as PRELOAD
function add_rel_preload($html, $handle, $href, $media) {
    if (is_admin()) {return $html;}

	$html = '<!--'.$handle.'-->'.$html;
	if( $handle=='infocus-style' || $handle=='wp-block-library' ){
		$html ='<link rel="preload" href="'.$href.'" as="style" onload="this.onload=null;this.rel=\'stylesheet\'" id="'.$handle.'" media="all"><noscript><link rel="stylesheet" href="'.$href.'"></noscript>';
	}
    return $html;
}
add_filter( 'style_loader_tag', 'add_rel_preload', 10, 4 );

Validate CF7 email address field

/* validate email address on forms */
add_filter( 'wpcf7_validate_email*', 'custom_email_confirmation_validation_filter', 20, 2 );
function custom_email_confirmation_validation_filter( $result, $tag ) {
	if ( 'your-email-confirm' == $tag->name ) {
		$your_email = isset( $_POST['your-email'] ) ? trim( $_POST['your-email'] ) : '';
		$your_email_confirm = isset( $_POST['your-email-confirm'] ) ? trim( $_POST['your-email-confirm'] ) : '';
	  
		if ( $your_email != $your_email_confirm ) {
		  $result->invalidate( $tag, "Email addresses do not match, please check and try again" );
		}
	}
	return $result;
}

Full width Gutenberg editor

// Full width Gutenberg editor
add_action('admin_head', 'editor_full_width_gutenberg');
function editor_full_width_gutenberg() {
  echo '<style>
    .block-editor__container .wp-block {
        max-width: none !important;
	}
	.editor-styles-wrapper {
	    padding: 5% !important;
	} 
    /*code editor*/
    .edit-post-text-editor__body,edit-post-visual-editor {
    	max-width: none !important;	
    	margin-left: 5%;
    	margin-right: 5%;
    }
  </style>';
}
// add styles to gutenberg
function gutenbergtheme_editor_styles() {
    wp_enqueue_style( 'gutenbergtheme-blocks-style', get_template_directory_uri() . '/blocks.css');
}
add_action( 'enqueue_block_editor_assets', 'gutenbergtheme_editor_styles' );

Expires headers

<IfModule mod_expires.c>
  ExpiresActive On

  # Images
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/gif "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/webp "access plus 1 year"
  ExpiresByType image/svg+xml "access plus 1 year"
  ExpiresByType image/x-icon "access plus 1 year"

  # Video
  ExpiresByType video/mp4 "access plus 1 year"
  ExpiresByType video/mpeg "access plus 1 year"

  # CSS, JavaScript
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType text/javascript "access plus 1 month"
  ExpiresByType text/x-javascript "access 1 month"
  ExpiresByType application/javascript "access plus 1 month"

  # Others
  ExpiresByType application/pdf "access plus 1 month"
  ExpiresByType application/x-shockwave-flash "access plus 1 month"
</IfModule>

Add woocommerce product category description to main wordpress search

The only way I could find to do this was to search for the terms separately and then insert the results before the main result (only on page 1 though).

add_action( 'loop_start', function(){
  $searchvar = get_search_query();
  $paged = get_query_var('paged'); 
  $debug = 'search: '. $searchvar;
  // only show on seach page and only for first page of results
  if($searchvar>'' && $paged==0){
	$s = $searchvar;
	$results = array();
	$searchterms = explode(' ',$s); // "+" is removed!
	//print_r($searchterms);
	$termcount=0;
	foreach($searchterms as $searchterm){
		$debug .= '

' . $searchterm . '
--------------------------'; $termcount++; $exclude_arr = array(); ${'termsfound'.$termcount} = array($searchterm); // search product category title $debug .= '

category title'; $terms = get_terms(array( 'taxonomy' => 'product_cat', 'name__like' => $searchterm, 'hide_empty' => true, // Optional )); if ( count($terms) > 0 ){ foreach ( $terms as $term ) { $results[] = $term; $exclude_arr[] = $term->term_id; ${'termsfound'.$termcount}[] = $term->term_taxonomy_id; } $debug .= '
excluded=' . implode(',',$exclude_arr); $debug .= '
terms=' . implode(',',${'termsfound'.$termcount}); } // search product category description $debug .= '

category description'; $exclude = implode(",", $exclude_arr); $terms2 = get_terms(array( 'taxonomy' => 'product_cat', 'description__like' => $searchterm, 'hide_empty' => true, // Optional 'exclude' => $exclude, )); if ( count($terms2) > 0 ){ foreach ( $terms2 as $term2 ) { $results[] = $term2; $exclude_arr[] = $term2->term_id; ${'termsfound'.$termcount}[] = $term2->term_taxonomy_id; } $debug .= '
excluded=' . implode(',',$exclude_arr); $debug .= '
terms2=' . implode(',',${'termsfound'.$termcount}); } // search product category acf description2 field $debug .= '

acf description2 field'; $exclude = implode(",", $exclude_arr); $description2terms = get_terms(array( 'taxonomy' => 'product_cat', 'hide_empty' => true, 'exclude' => $exclude, 'meta_query' => array( array( 'key' => 'description_2', 'value' => $searchterm, 'compare' => 'LIKE' ), ), )); if ( count($description2terms) > 0 ){ foreach ( $description2terms as $term3 ) { $results[] = $term3; ${'termsfound'.$termcount}[] = $term3->term_taxonomy_id; } $debug .= '
terms3=' . implode(',',${'termsfound'.$termcount}); } } if ($termcount>1) { // search is AND, therefore only show results which appear in all result sets $commonterms = $termsfound1; for ($i=2; $i<=$termcount; $i++) { $commonterms = array_intersect($commonterms, ${'termsfound'.$i}); } $commonterms = array_values($commonterms); if(count($commonterms) > 0){ $debug .= '

common terms=' . implode(',',$commonterms); $terms3 = get_terms(array( 'taxonomy' => 'product_cat', 'include' => $commonterms, )); foreach ( $terms3 as $term ) { $finalresults[] = $term; } } else { $finalresults = array(); // no common results //echo 'NOTHING!'; } } else { $finalresults = $results; // one one term searched for } //echo '
'; echo $debug; echo '

';
// combine results
if ( count($finalresults) > 0 ){
/* [term_id] [name] [slug] [term_group] [term_taxonomy_id] [taxonomy] [description] [parent] [count] [filter] [term_order] */
foreach ( $finalresults as $result ) {
$thumbnail_id = get_woocommerce_term_meta( $result->term_id, 'thumbnail_id', true );
$imageurl = wp_get_attachment_image_url( $thumbnail_id, 'swiper_news_image_size' );
$imageurlsm = wp_get_attachment_image_url( $thumbnail_id, 'post_image_thumb' );
//$excerpt = esc_html( $result->description );
$excerpt = substr(esc_html( $result->description ),0,strpos(esc_html( $result->description ),' ',250));
echo '

';
}
}
}
});

Gutenburg block editor styles

New JS file (eg theme/js/editor.js)

wp.domReady( () => {
    wp.blocks.registerBlockStyle( ‘core/paragraph’, [
        {
            name: ‘default’,
            label: ‘Default’,
            isDefault: true,
        },
        {
            name: ‘intro’,
            label: ‘Intro’,
        }
    ]);
} );

 

New editor CSS file (eg theme/my-editor.css)


/* Block editor styles */
p.is-style-intro {font-size:30px!important;line-height:40px!important;} /* seem to need "!important" for font-size & line height */
/* tweaks to make block editor preview look more accurate */
.block-editor-block-preview__content p.is-style-intro {font-size:40px!important;line-height:60px!important; font-weight: bold;} /* little preview */
.block-editor-block-switcher__preview p.is-style-intro {font-size:40px!important;line-height:60px!important;} /* larger pop-out preview */

Functions file additions

/**
 * Gutenberg scripts and styles
 * @link https://www.billerickson.net/block-styles-in-gutenberg/
 *
 * enqueue_block_editor_assets = load in backend only
 * enqueue_block_assets = load in front and backend
 */
function be_gutenberg_scripts() {
    wp_enqueue_script(
        ‘be-editor’,
        get_stylesheet_directory_uri() . ‘/js/editor.js’,
        array( ‘wp-blocks’, ‘wp-dom’ ),
        filemtime( get_stylesheet_directory() . ‘/js/editor.js’ ),
        true
    );
}
add_action( ‘enqueue_block_editor_assets’, ‘be_gutenberg_scripts’ );
function be_gutenberg_styles() {
    wp_enqueue_style(
        ‘be-editor-styles’,
        get_stylesheet_directory_uri() . ‘/my-editor-styles.css’,
        false,
        filemtime( plugin_dir_path( __FILE__ )  . ‘my-editor-styles.css’ )
    );
}
add_action( ‘enqueue_block_editor_assets’, ‘be_gutenberg_styles’ );

 

And style for front end!
p.is-style-intro {font-size: 30px;line-height: 40px;color:magenta;}

Admin dashboard notes and help tab content


// dashboard notes
function add_custom_dashboard_widgets() {
wp_add_dashboard_widget(
'wpexplorer_dashboard_widget', // Widget slug.
'Admin notes', // Title.
'custom_dashboard_widget_content' // Display function.
);
}
add_action( 'wp_dashboard_setup', 'add_custom_dashboard_widgets' );
function custom_dashboard_widget_content() {
echo "

Hello, please remember to stay away from the plugins menu.

Here are some important notes:

  • Datatables The data table ID must be set to the same as the product ID it is linked to.

If you have any need of assistance, please don't hesitate to contact us under:

  • https://www.d2creative.co.uk/
  • 01392 877116

";
}
// add help tab content
function setup_help_tab() {
$screen = get_current_screen();
if ( 'post' == $screen->post_type ) {
get_current_screen()->add_help_tab( array(
'id' => 'post',
'title' => ( 'How to Publish a Blog Post' ),
'content' => '

To publish a blog post, please follow the steps below.

  • Locate big, blue Publish button.
  • Click it.
  • Well done.

',
) );
}
}
// add more here
add_action( 'admin_head', 'setup_help_tab' );

Change “Posts” to “News” in WP Admin menu

function revcon_change_post_label() {
global $menu;
global $submenu;
$menu[5][0] = 'News';
$submenu['edit.php'][5][0] = 'News';
$submenu['edit.php'][10][0] = 'Add News';
$submenu['edit.php'][16][0] = 'News Tags';
}
function revcon_change_post_object() {
global $wp_post_types;
$labels = &$wp_post_types['post']->labels;
$labels->name = 'News';
$labels->singular_name = 'News';
$labels->add_new = 'Add News';
$labels->add_new_item = 'Add News';
$labels->edit_item = 'Edit News';
$labels->new_item = 'News';
$labels->view_item = 'View News';
$labels->search_items = 'Search News';
$labels->not_found = 'No News found';
$labels->not_found_in_trash = 'No News found in Trash';
$labels->all_items = 'All News';
$labels->menu_name = 'News';
$labels->name_admin_bar = 'News';
}

add_action( 'admin_menu', 'revcon_change_post_label' );
add_action( 'init', 'revcon_change_post_object' );

Custom post type with custom taxonomy in permalink

Custom post type

// Case studies custom post type
// based on https://wisdmlabs.com/blog/add-taxonomy-term-custom-post-permalinks-wordpress/
add_action('init', 'projects_cpt');
function projects_cpt() {
$labels = array(
'name' => 'Case studies',
'singular_name' => 'Case study',
'add_new' => 'Add New',
'add_new_item' => 'Add New Case study',
'edit_item' => 'Edit Case study',
'new_item' => 'New Case study',
'all_items' => 'All Case studies',
'view_item' => 'View Case study',
'search_items' => 'Search Case studies',
'not_found' => 'No Case studies found',
'not_found_in_trash' => 'No Case studies found in Trash',
'parent_item_colon' => '',
'menu_name' => 'Case studies'
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'taxonomies' => array('industrytype'),
'rewrite' => array('slug' => 'industries/%casestudycategory%/case-studies', 'with_front' => false),
//Adding custom rewrite tag
'capability_type' => 'post',
//'has_archive' => 'projectsarchives',
'has_archive' => false,
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title', 'editor', 'author', 'thumbnail', 'excerpt'),
);
register_post_type('casestudy', $args);

$labels = array(
‘name’ => ‘Case study Categories’,
‘singular_name’ => ‘Case studies’,
‘search_items’ => ‘Search Case study Categories’,
‘all_items’ => ‘All Case study Categories’,
‘parent_item’ => ‘Parent Case study Category’,
‘parent_item_colon’ => ‘Parent Case study Category:’,
‘edit_item’ => ‘Edit Case study Category’,
‘update_item’ => ‘Update Case study Category’,
‘add_new_item’ => ‘Add New Case study Category’,
‘new_item_name’ => ‘New Case study Category’,
);

$args = array(
‘hierarchical’ => true,
‘rewrite’ => array(‘slug’ => ‘case-studies’),
‘show_in_nav_menus’ => true,
‘show_admin_column’ => true,
‘labels’ => $labels
);

register_taxonomy(‘casestudycategory’, ‘casestudy’, $args);

unset($labels);
unset($args);
}

add_filter(‘post_type_link’, ‘projectcategory_permalink_structure’, 10, 4);
function projectcategory_permalink_structure($post_link, $post, $leavename, $sample) {
if (false !== strpos($post_link, ‘%casestudycategory%’)) {
// get all terms
$casestudycategory_type_term = get_the_terms($post->ID, ‘casestudycategory’);

if (!empty($casestudycategory_type_term)){
// find primary term
$primarycat = ‘x’;
$primarray = get_post_meta($post->ID,’_yoast_wpseo_primary_casestudycategory’);
foreach ( $casestudycategory_type_term as $term ) {
if( $primarray[0] == $term->term_id ) {
// this is a primary category
$primarycat = $term->slug;
}
}
if ($primarycat == ‘x’) {
$primarycat = array_pop($casestudycategory_type_term)->slug;
}
$post_link = str_replace(‘%casestudycategory%’, $primarycat, $post_link);
} else {
$post_link = str_replace(‘%casestudycategory%’, ‘uncategorized’, $post_link);
}
}
return $post_link;
}
// redirect automatic-casestudy-archive pages to actual pages
function custom_event_rewrite_one() {
add_rewrite_rule(    ‘^industries/([^/]+)/case-studies/?$’,
‘index.php?pagename=industries%2F$matches[1]%2Fcase-studies’,
‘top’);
add_rewrite_rule(    ‘^industries/([^/]+)/?$’,
‘index.php?pagename=industries%2F$matches[1]’,
‘top’);
}
add_action(‘init’,’custom_event_rewrite_one’);

Shortcode to display list of custom posts

// shortcode to list case studies with option to filter by casestudy category [listcasestudies cscat="automotive"]
function cdk_get_casestudies( $atts ) {

$atts = shortcode_atts( array(
‘cscat’ => ”
), $atts );

$args = [
‘post_type’      => ‘casestudy’,
‘posts_per_page’ => ‘-1’,
‘order’          => ‘DESC’,
‘orderby’        => ”,
];

if ( $atts[‘cscat’] ) {
$args[‘tax_query’] = [
[
‘taxonomy’ => ‘casestudycategory’,
‘field’    => ‘slug’,
‘terms’     => array( sanitize_title( $atts[‘cscat’] ) )
]
];
}

$the_query2 = new WP_Query( $args );
$output2 = ”;

if ( $the_query2->have_posts() ) {
while ( $the_query2->have_posts() ) {
$the_query2->the_post();

$terms = get_the_terms( get_the_ID(), ‘casestudycategory’ );
$all_cats = array();

$primarycat = ‘x’;
$primarray = get_post_meta(get_the_ID(),’_yoast_wpseo_primary_casestudycategory’);

if ( $terms && !is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
$all_cats[] = $term->name . ‘(‘.$term->term_id.’)’;

if( $primarray[0] == $term->term_id ) {
// this is a primary category
$primarycat = $term->slug;
}
}
}
$all_cats_str = join( “, “, $all_cats );
$first_cat_slug = $terms[0]->slug;
if ($primarycat == ‘x’) {
$primarycat = $first_cat_slug;
}

if ( $atts[‘cscat’] ) { // display for specific category
$output2 .= ‘<p> * <a href=”‘ . get_permalink() .'”>’. get_the_title() .'</a></p>’;
} else {
$output2 .= ‘<p> * <a href=”‘ . get_permalink() .'”>’. get_the_title() .'</a></p>’;
}
$output2 .= ‘<p>primary cat = ‘.$primarycat.’
<br>all = ‘.$all_cats_str.'</p>’;
}
wp_reset_postdata();
} else {
$output2 .= ‘<p>No case studies…</p>’;
}

return $output2;

}
add_shortcode(‘listcasestudies’, ‘cdk_get_casestudies’);

Elementor addons

https://livemeshelementor.com/posts-carousel/
posts carosel

https://www.elementoraddons.com/elements-addon-elements/background-image-slider/
Background image slider