Useful WordPress Utility Functions for Theme and Plugin Development

Useful WordPress functions for themes

Exactly one month ago I published an article about useful WooCommerce functions. This one is a kind of continuation, but here are only WordPress functions (and a couple for ACF) that I use in almost every project. They all go into functions.php.

0. Output an ACF link

<?php
function the_custom_acf_link( $title, $url, $target, $class = '' ) {
    if ( ! $url ) {
        return;
    }

    $target = $target ? '_blank' : '_self';
    $class  = $class ? ' class="' . esc_attr( preg_replace( '/[^ \w-]+/', '', $class ) ) . '"' : '';

    echo '<a href="' . esc_url( $url ) . '"' . $class . ' target="' . $target . '">' . esc_html( $title ) . '</a>';
}

With an ACF Link field it is called like this:

<?php
$link = get_field( 'button' );
if ( $link ) {
    the_custom_acf_link( $link['title'], $link['url'], $link['target'], 'btn btn-primary' );
}

1. Output an ACF image

For an Image field with the return format “Image Array”:

<?php
function the_custom_acf_image( $image, $class = '' ) {
    if ( empty( $image['url'] ) ) {
        return;
    }

    $class = $class ? ' class="' . esc_attr( preg_replace( '/[^ \w-]+/', '', $class ) ) . '"' : '';

    echo '<img' . $class . ' src="' . esc_url( $image['url'] ) . '" alt="' . esc_attr( $image['alt'] ) . '">';
}

If you only need an image size with srcset, wp_get_attachment_image( $image['ID'], 'large' ) does it too.

2. Check whether a category has children

<?php
function category_has_children( $term_id = 0, $taxonomy = 'category' ) {
    $children = get_terms( array(
        'taxonomy'   => $taxonomy,
        'parent'     => $term_id,
        'hide_empty' => false,
        'number'     => 1,
        'fields'     => 'ids',
    ) );

    return ! empty( $children ) && ! is_wp_error( $children );
}

One child is enough for the answer, so the query is limited to one ID.

3. Disable updates of one plugin

Useful when a plugin has been modified and an update would overwrite the changes:

<?php
add_filter( 'site_transient_update_plugins', 'disable_plugin_updates' );

function disable_plugin_updates( $value ) {
    if ( is_object( $value ) && isset( $value->response['plugin-folder/plugin.php'] ) ) {
        unset( $value->response['plugin-folder/plugin.php'] );
    }
    return $value;
}

plugin-folder/plugin.php is the path of the main plugin file relative to wp-content/plugins.

4. Allow uploading JSON files

<?php
add_filter( 'upload_mimes', 'allow_json_upload' );

function allow_json_upload( $mime_types ) {
    $mime_types['json'] = 'application/json';
    return $mime_types;
}

5. Render page builder sections

For an ACF Flexible Content field: every layout is a separate template file named after the layout, for example sections/hero.php:

<?php
function render_sections( $field = 'sections' ) {
    // Exit early if ACF is not active
    if ( ! function_exists( 'have_rows' ) ) {
        return;
    }

    while ( have_rows( $field ) ) {
        the_row();
        $template = locate_template( $field . '/' . get_row_layout() . '.php' );
        if ( $template ) {
            include $template;
        }
    }
}

In the template you only need render_sections();, and inside each section file get_sub_field() works as usual.

6. Post views counter

<?php
function set_post_views( $post_id ) {
    $count_key = 'post_views_count';
    $count     = (int) get_post_meta( $post_id, $count_key, true );
    update_post_meta( $post_id, $count_key, $count + 1 );
}

// To keep the count accurate, remove the prefetch links to adjacent posts
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10 );

add_action( 'wp_head', 'track_post_views' );

function track_post_views() {
    if ( is_singular( array( 'post', 'news', 'event' ) ) ) {
        set_post_views( get_the_ID() );
    }
}

Then popular posts are a normal query with 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num'. The counter counts every page view, including bots and reloads, and it does not work behind a full page cache: the cached page does not run PHP.

7. Get a user ID by display name

<?php
function get_user_id_by_display_name( $display_name ) {
    global $wpdb;

    $user_id = $wpdb->get_var( $wpdb->prepare(
        "SELECT ID FROM {$wpdb->users} WHERE display_name = %s LIMIT 1",
        $display_name
    ) );

    return $user_id ? (int) $user_id : false;
}

Display names are not unique, so if several users have the same name, this returns the first one.

Sources:

  1. https://gist.github.com/rniswonger/ee1b30e5fd3693bb5f92fbcfabe1654d
  2. https://www.wpbeginner.com/wp-tutorials/how-to-track-popular-posts-by-views-in-wordpress-without-a-plugin/