Blog

Display image with srcet from ACF image field

function acfimg( $img ) {
$img_srcset = wp_get_attachment_image_srcset( $img[‘ID’] );
$img_sizes = wp_get_attachment_image_sizes( $img[‘ID’] );
echo ‘'.$img['alt'].'‘;
}


Hide Yoast Meta Boxes

function hide_yoast_seo_meta_box_for_cpt() {
remove_meta_box( ‘wpseo_meta’, ‘testimonials’, ‘normal’ );
remove_meta_box( ‘wpseo_meta’, ‘faqs’, ‘normal’ );
remove_meta_box( ‘wpseo_meta’, ‘links’, ‘normal’ );
remove_meta_box( ‘wpseo_meta’, ‘team’, ‘normal’ );
remove_meta_box( ‘wpseo_meta’, ‘events’, ‘normal’ );
remove_meta_box( ‘wpseo_meta’, ‘volunteer_events’, ‘normal’ );
}
add_action( ‘add_meta_boxes’, ‘hide_yoast_seo_meta_box_for_cpt’, 99 );


Center image vertically in DIV

<div class="container d-flex align-items-center justify-content-center min-vh-100">
<h1>Centered Element</h1>
</div>

Remove not required menu items for Editors

function remove_menus() {
if ( !current_user_can( ‘administrator’ ) ) {
remove_menu_page(‘edit.php’);
remove_menu_page(‘edit-comments.php’);
remove_menu_page(‘tools.php’);
remove_menu_page(‘wpseo_workouts’);
remove_submenu_page(‘wpseo_workouts’, ‘wpseo_redirects’);
remove_submenu_page(‘wpseo_workouts’, ‘wpseo_workouts’);
}
}
add_action( ‘admin_menu’, ‘remove_menus’ );


Allow Editor to edit Privacy Policy Page

add_filter( ‘map_meta_cap’, ‘manage_privacy_options’, 1, 4 );
function manage_privacy_options( $caps, $cap, $user_id, $args ) {
if ( !is_user_logged_in() ) return $caps;

if ( 'manage_privacy_options' === $cap ) {
    $manage_name = is_multisite() ? 'manage_network' : 'manage_options';
    $caps = array_diff( $caps, [ $manage_name ] );
}
return $caps;

}


Bootstrap 5 Menu Drop Down and Navigate


// The drop down menu needs to allow for navigation to parent as well as drop down.
// This javascript will find all instances of .dropdown-toggle (parent menu items) and if there is
// a .show class (ie; the submenu is showing), it will change to default behaviour (href navigation).
// If no .show class, bootstrap behaviour should be activated. // Target all parent menu items with a dropdown-toggle
const dropdownToggles = document.querySelectorAll('.dropdown-toggle');
dropdownToggles.forEach(function(dropdownToggle) {
const dropdownMenu = dropdownToggle.nextElementSibling; // Get the corresponding dropdown menu
const dropdown = dropdownToggle.closest('.dropdown'); // Get the closest dropdown container // Manually track the dropdown visibility state let isDropdownVisible = false; // Attach the click event to each parent link dropdownToggle.addEventListener('click', function(e) { e.preventDefault(); // Prevent Bootstrap's default behavior of toggling the dropdown if (isDropdownVisible) { // If the dropdown is open, navigate to the link window.location.href = dropdownToggle.href; // Navigate to the href } else { // If the dropdown is not open, show it and prevent navigation const bsDropdown = new bootstrap.Dropdown(dropdownToggle); bsDropdown.show(); // Explicitly show the dropdown without navigating // Update our manually tracked state isDropdownVisible = true; } });

});


Stay logged into WordPress

    function stay_logged_in($expires) {
    return 172800; // default 48 hours
    // return YEAR_IN_SECONDS;
    }
    add_filter(‘auth_cookie_expiration’, ‘stay_logged_in’);


    WordPress Admin Stylesheet

    To include styling for Administrators:

    function admin_style() {
    wp_enqueue_style(‘admin-styles’, get_template_directory_uri().’/admin.css’);
    }
    add_action(‘admin_enqueue_scripts’, ‘admin_style’);


    WordPress Categories Template

    If WordPress category template file is not working, add the following in category.php, before the loop:

    $cat_id = get_query_var(‘cat’);
    query_posts(“post_type=&cat=$cat_id”);


    Page Navigation by Category

    $terms = get_the_terms( $post->ID, ‘mediaitem’ );
    $args = array(
    ‘in_same_term’ => true,
    ‘category’ => $term->slug,
    ‘screen_reader_text’ => ‘Post navigation’
    );
    the_post_navigation($args);


    WordPress: Loop All Categories showing All Posts

    $post_type = ‘category’;
    $args = array(
    ‘true’ => false,
    ‘orderby’ => ‘term_id’,
    ‘order’ => ‘ASC’
    );
    $tax = get_terms( ‘category’ , $args);
    if ( have_posts() ) {
    foreach( $tax as $cat ) {
    echo $cat->name;
    while ( have_posts() ) : the_post();
    the_title();
    the_content();
    endwhile;
    }
    }


    Useful WordPress Development Plugins

    Replace WordPress Media with Enable Media Replace

    Audit WordPress changes using Stream

    Change WordPress administrator menu options with Admin Menu Editor

    Simplify Look and feel for WordPress Editors with White Label CMS

    Easy WordPress Updates Manager with Easy Updates Manager


    WordPress: Easy to remember template hierarchy

    Aide memoir for the WordPress template hiearchy…

    Default for everything – archive pages, single posts and single pages (as well as all other content types):

    1st: index.php

    Select template by page for specific archive displays, like category and taxonomy archives or templates for different page layouts:

    1st: template_{$custom-post-type}.php or template_{NOSIDEBAR}.php
    2nd: index.php

    For all pages that do not exist:

    1st: 404.php
    2nd: index.php

    The user submits a search:

    1st: search.php
    2nd: index.php

    Latest blog posts:

    1st: front-page.php
    2nd: home.php
    3rd: index.php

    For whichever page is assigned as the front page:

    1st: front-page.php
    2nd: home.php
    3rd: index.php

    For a single post page:

    1st: single-{$post-type}-{$slug}.php
    2nd: single-{$post-type}.php
    3rd: single.php
    4th: singular.php (fallback for single.php AND page.php)
    3rd: index.php

    For a single page:

    1st: custom_template.php
    2nd: page-{$slug}.php
    3rd: page-{$id}.php
    4th: page.php
    5th: singular.php (fallback for single.php AND page.php)
    6th: index.php

    For a category page:

    1st: category-{$slug}.php
    2nd: category-{$id}.php
    3rd: category.php
    4th: archive.php
    5th: index.php

    for a tag page:

    1st: tag-{$slug}.php
    2nd: tag-{$id}.php
    3rd: tag.php
    4th: archive.php
    5th: index.php

    For custom taxonomy pages:

    1st: taxonomy-{$taxonomy}-{$term}.php
    2nd: taxonomy-{$taxonomy}.php
    3rd: taxonomy.php
    4th: archive.php
    5th: index.php

    For Custom Post Types:

    1st: archive-{post_type}.php
    2nd: archive.php
    3rd: index.php

    For an author info page:

    1st: author-{$author-nicename}.php
    2nd: author-{$author-id}.php
    3rd: author.php
    4th: archive.php
    5th: index.php

    For a date page archive:

    1st: date.php
    2nd: archive.php
    3rd: index.php

    For an attachment page:

    1st: {$MIME-type}.php (one of: image.php, video.php, pdf.php, application.php, etc.)
    2nd: attachment.php
    3rd: single-attachment-{$slug}.php
    4th: single-attachment.php
    5th: single.php
    6th: singular.php
    7th: index.php

    For embeds:
    1st: embed-{$post-type}-{$post_format}.php
    2nd: embed-{$post-type}.php
    3rd: embed.php
    4th: wp-includes/theme-compat/embed.php


    WordPress: useful additions to functions.php

    /*
    * Useful snippets for functions.php
    /*

    /*
    * Add support for the following:
    */
    add_theme_support( ‘title-tag’ );
    add_theme_support( ‘post-thumbnails’ );
    add_theme_support( ‘html5’, array( ‘search-form’, ‘comment-form’, ‘comment-list’ ) );

    /*
    * Register Menus
    */
    function register_my_menus(){
    register_nav_menus(
    array( ‘primary’ => __(‘Primary Menu’, ‘AD’), ) );
    }
    add_action(‘init’, ‘register_my_menus’);

    /*
    * Allow php in widget
    */
    function howman_php_execute( $html ) {
    if ( strpos($html,”<“.”?php”) !==false ) {
    ob_start();
    eval(“?”.”>”.$html);
    $html=ob_get_contents();
    ob_end_clean();
    }
    return $html;
    }
    add_filter(‘widget_text’,’howman_php_execute’, 100);

    /*
    *Enqueue Datepicker + jQuery UI CSS
    */
    wp_enqueue_script( ‘jquery-ui-datepicker’ );
    wp_enqueue_style( ‘jquery-ui-style’, ‘//ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/smoothness/jquery-ui.css’, true);

    /*
    * Add widgets
    */
    function bootstrapstarter_widgets_init() {

    register_sidebar( array(
    ‘name’ => ‘Footer – Copyright Text’,
    ‘id’ => ‘footer-copyright-text’,
    ‘before_widget’ => ‘<div class=”footer_copyright_text”>’,
    ‘after_widget’ => ‘</div>’,
    ‘before_title’ => ‘<h4>’,
    ‘after_title’ => ‘</h4>’,
    ) );

    register_sidebar( array(
    ‘name’ => ‘Sidebar – Inset’,
    ‘id’ => ‘sidebar-1’,
    ‘before_widget’ => ‘<div class=”sidebar-module sidebar-module-inset”>’,
    ‘after_widget’ => ‘</div>’,
    ‘before_title’ => ‘<h4>’,
    ‘after_title’ => ‘</h4>’,
    ) );

    register_sidebar( array(
    ‘name’ => ‘Sidebar – Default’,
    ‘id’ => ‘sidebar-2’,
    ‘before_widget’ => ‘<div class=”sidebar-module”>’,
    ‘after_widget’ => ‘</div>’,
    ‘before_title’ => ‘<h4>’,
    ‘after_title’ => ‘</h4>’,
    ) );

    }
    add_action( ‘widgets_init’, ‘bootstrapstarter_widgets_init’ );

    /*
    * Register jQuery
    */
    if (!is_admin()) {
    wp_deregister_script(‘jquery’);
    wp_register_script(‘jquery’, (“https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js”), false);
    wp_enqueue_script(‘jquery’);
    }

    /*
    * Custom Excerpt Length
    */
    function custom_excerpt_length($length) {
    return 25;
    }
    add_filter(‘excerpt_length’, ‘custom_excerpt_length’);

    /*
    * Add scripts, stylesheets, fonts, etc.
    */
    function mysite_enqueue_styles() {
    wp_register_style(‘bootstrap’, get_template_directory_uri() . ‘/bootstrap/css/bootstrap.min.css’ );
    $dependencies = array(‘bootstrap’);
    wp_enqueue_style( ‘mysite-style’, get_stylesheet_uri(), $dependencies );
    }
    add_action( ‘wp_enqueue_scripts’, ‘mysite_enqueue_styles’ );

    function startwordpress_scripts() {
    wp_enqueue_script( ‘bootstrap’, get_template_directory_uri() . ‘/js/bootstrap.min.js’, array( ‘jquery’ ), ‘3.3.6’, true );
    wp_enqueue_script( ‘validator’, get_template_directory_uri() . ‘/js/jquery.validate.min.js’, array ( ‘jquery’ ), ‘3.3.6’, true);
    }
    add_action( ‘wp_enqueue_scripts’, ‘startwordpress_scripts’ );

    function startwordpress_google_fonts() {
    wp_register_style(‘Lato’, ‘http://fonts.googleapis.com/css?family=Lato:100,200,400,600,700,800’);
    wp_enqueue_style( ‘Lato’);
    wp_register_style(‘Nunito’, ‘https://fonts.googleapis.com/css?family=Nunito+Sans” rel=”stylesheet”>’);
    wp_enqueue_style( ‘Nunito’);
    // wp_register_style(‘OpenSans’, ‘https://fonts.googleapis.com/css?family=Open+Sans” rel=”stylesheet”>’);
    // wp_enqueue_style( ‘OpenSans’);
    }
    add_action(‘wp_print_styles’, ‘startwordpress_google_fonts’);


    WordPress: Must have plugins, updated

    Must Haves

    All In One SEO Pack
    Out-of-the-box SEO for your WordPress blog.

    WordFence
    THE security plugin.

    WP Optimize
    Clean Up / Optimise your WordPress installation.

    WP Super Cache
    WordPress Caching.

    WP Smush It
    Optimise graphics files.

    WP Migrate DB
    WordPress database migration.

    Used in Specific Circumstances

    Advanced Custom Fields
    Provides simple flexibility.

    Post Types Order
    Provides simple and easy sorting.

    Superceded

    These we still use occassionally, but simpler to build on the fly:

    Contact Form 7

    These we no longer used as they’re all done by All in One SEO:

    Google Analytics for WordPress
    Google XML Sitemaps


    WordPress: Show title and alt on images

    To add image alt and title attributes to images, add the following to functions.php:
    function add_image_title( $attr, $attachment= null ) {
        $img_title= trim( strip_tags( $attachment->post_title ) );
        $attr['title'] = $img_title;
        $attr['alt'] = $img_title;
        return$attr;
    }
    add_filter( 'wp_get_attachment_image_attributes','add_imgage_title', 10, 2 );
    or replace $attr[‘title’] with:
    $attr['title'] = the_title_attribute( 'echo=0' );

    WordPress: Two Columns using More button

    1) Ensure you have added <!–more–>  in page content. Use the more button!

    2) Use the following code to display content in two columns:
    global $more;
    $more = 0;
    echo ‘<div id=”column_one”>’;
    echo ‘&nbsp;’;
    the_content(”);
    echo ‘</div>’;

    $more = 1;
    echo ‘<div id=”column_two”>’;
    the_content(‘read more’, true);
    echo ‘</div>’;

    3) CSS to tidy it up:
    #column_one, #column_two {
    float: left;
    width: 35%;
    margin: 0px 7.5%;
    }
    #column_one {
    padding-left: 5%;
    }
    #column_two {
    padding-right: 5%;
    }
    #column_one h6, #column_two h6 {
    display: none;
    }
    #column_one p, #column_two p {
    text-align: center;
    }


    WordPress: List all queries on the page

    This code snippet will list all the queries executed on your WordPress page
    Add this to the bottom of the page:

    <?php
    if (current_user_can(‘administrator’)){
    global $wpdb;
    echo “<pre>”;
    print_r($wpdb->queries);
    echo “</pre>”;
    }
    ?>


    WordPress: different CSS for different objects

    Site:

    body {
    background-image:url(‘background.jpg’);
    }

    Single Page:

    body.page-id-78 {
    background-image:url(‘background.jpg’);
    }

    Several Pages:

    body.page-id-78, body.page-id-79, body.page-id-82 {
    background-image:url(‘background.jpg’);
    }

    Single Category:

    .category-CatName {
    background-image:url(‘background.jpg’);
    }

    Multiple Categories:

    .category-CatName1, .category-CatName-2 {
    background-image:url(‘background.jpg’);
    }

    Archive Pages:

    .archive {
    background-image:url(‘background.jpg’);
    }

    Custom Template, Post or Category:

    .page-template-name {
    background-image:url(‘background.jpg’);
    }


    What do Web Developers Do?

    Excellent list of skills required to be a web developer in 2015: See here.


    Web Site Objectives

    As with any other aspect of your business, you want to know that your website is working for you. Just as you wouldn’t keep spending money on television advertisements or glossy brochures unless they were helping you to achieve your business goals, nor should your website go unchecked. The first step is to clearly understand the purpose of your website and how it meets your business objectives.

    Ideally before you spent the time and money building a website you would have thought about why you were doing it. In reality most businesses build a website because they believe that it is a “must” in today’s business environment. Common website formats are –

    1) Brochure site. The online equivalent of your company’s brochure. The customer needs to contact the company to conduct a transaction.

    2) Ecommerce site. An online shop. Customers can search for products, compare and purchase online.

    3) Community site. The company can provides competitions, games or forums for customers to share ideas and stories while gathering important customer insights.

    The type of site you have will depend on your business and may include a combination of those listed above. It is very important to keep in mind the reality of your business. If you have a complex product that requires a detailed consultative sales process, it is probably not realistic to have an E-Commerce site.

    Now look at your business objectives. See how for each business goal your action plan includes marketing activities to help achieve it? Well, your website is part of your marketing mix. So highlight each business objective that you think can be achieved or assisted by your website. Now you are ready to write your web objectives. You should always use SMART objectives (Specific, Measurable, Achievable, Realistic, Time-specific).

    An overview of setting your website objectives might look like this:

    1) Clearly define your business goals. Example: “To reduce the average cost per sale by 25%”
    2) Identify which goals are best supported by which aspects of the marketing mix, including web. Example: Mail, online and telephone orders have a lower average sales cost.
    3) Set your marketing objectives. Example: To have 40% of sales being completed via mail (10%), telephone (5%) and web (25%) by the end of financial year.
    4) Break down web specific objectives. Example: To achieve £250,000 (25% of projected sales) via the website by the end of financial year.

    In this way, you will have a very clear idea of what your website needs to achieve. Luckily websites are highly measurable so you will have plenty of statistical help to guide you.

    We always encourage clients to think first of the busines solution they need and then ask their IT people to create it. Sadly we find most businesses do the opposite – they ask their IT people what they can make and then they try to fit it to their business.

    Here are some examples of things you might like to achieve on a business level and some of the web based solutions that can support these goals:

    1) Enter new geographical markets (including international) – online shop
    2) Create a database of potential customers – e-newsletter subscriptions or online competitions
    3) Produce sales leads for your sales people – online appointment booking, email contact, Skype linked phone numbers
    4) Reduce sales seminar costs and spread your geographical reach – online live streaming seminars with live video chat.


    WordPress, must have plugins

    All In One SEO Pack

    Out-of-the-box SEO for your WordPress blog.

    Contact Form 7

    Just another contact form plugin. Simple but flexible.

    Google Analytics for WordPress

    This plugin makes it simple to add Google Analytics to your WordPress blog, adding lots of features, eg. custom variables and automatic clickout and download tracking.

    Google XML Sitemaps

    This plugin will generate a special XML sitemap which will help search engines like Google, Yahoo, Bing and Ask.com to better index your blog.

    NextGEN Gallery

    A NextGENeration Photo gallery for the Web 2.0.

    Display Posts Shortcode

    The Display Posts Shortcode was written to allow users to easily display listings of posts without knowing PHP or editing template files.

    MapPress Easy Google Maps

    MapPress adds an interactive map to the wordpress editing screens. When editing a post or page just enter any addresses you’d like to map.


    Set Apache Root Directory

    How to Set the Apache Web Site Root Directory

    The DocumentRoot directive is used to specify the web server’s root directory, so if you make a request to http://localhost/
    Apache will map that address with the directory specified in DocumentRoot.

    Open up httpd.conf (in your Apache/conf directory), find DocumentRoot and set it to be your the directory where you want your web site root. If you are migrating from IIS you can put something like this: DocumentRoot “c:/inetpub/wwwroot”

    While you are doing this another directive you should set is called the ServerName directive. Set this to be the DNS name of your server (eg servername.company.com ) if you do not have a DNS name you can also use an IP address. Note that the newer versions of Apache preset this value with the installer.


    Installing Apache, PHP and MySQL

    Our recommendation is to always use XAMPP! Fast and easy to install, either on Windows or Linux, it does all the hard work for you. The 1.8.1 version of the toolset includes:

    • Apache 2.4.3
    • MySQL 5.5.27
    • PHP 5.4.7
    • phpMyAdmin 3.5.2.2

    The Control Panel includes service start and stop as well as options to configure and log errors.
    To install, download XAMPP from: Apache Friends, use the installer and follow the very simple instructions.


    WordPress Shortcut Icon (Favicon)

    In HTML, it’s relatively simple to add a Shortcut Icon, you would need to add the following between <head> and </head> in all your html pages:

    <link rel=”shortcut icon” href=”http://www.domain.com/favicon.ico” type=”image/x-icon”>The word ‘shortcut’ is not always used (ie; rel=”icon” is ok), it’s added for backwards browser compatibility.

    Only type=”image/gif”, type=”image/x-icon” and type=”image/png” are supported in all browsers.

    You could do the same in WordPress by adding the above between the <head> </head> tags in header.php in the relevant theme (http://www.domain.com/wp-content/themes/theme/header.php).

    However because the page is created dynamically, for correctness, the path is supplied as a variable:

    <link rel=”shortcut icon” href=”<?php echo get_stylesheet_directory_uri(); ?>/favicon.ico”>