Wordpress

WordPress Debug

// Enable WP_DEBUG mode
define(‘WP_DEBUG’, true);

// Enable Debug logging to the /wp-content/debug.log file
define(‘WP_DEBUG_LOG’, true);

// Disable display of errors and warnings
define(‘WP_DEBUG_DISPLAY’, false);
@ini_set(‘display_errors’, 0);

// Enable WordPress debugging for developers
define(‘WP_DEBUG_DISPLAY’, false);
define(‘SCRIPT_DEBUG’, true);

Paginating an Advanced Custom Fields Repeater

Hands down my favourite WordPress plugin is Elliot Condon’s Advanced Custom Fields, and it’s made even more powerful by the Repeater Field add-on. But a Repeater can get unwieldy when it contains a large number of items, and you might find yourself wanting to paginate the results when you display them to the user. Here’s a technique for doing that.

In this example we will paginate a Repeater image gallery mapped to a custom field named image_gallery with a sub field named image which contains an image object. Our Repeater will be displayed on a page at the URL /gallery.

10 images will be displayed per page, and pagination links will allow the user to navigate between the gallery’s pages at pretty URLS such as /gallery/2//gallery/3/ and so on.

If you’re wondering what special magic you need to perform to get those pretty permalinks working, the answer is… none! WordPress automagically converts URL segments such as /2/ into a query variable named "page". Very handy!

In your page template:

[php]

/* * Paginate Advanced Custom Field repeater */ if( get_query_var(‘page’) ) { $page = get_query_var( ‘page’ ); } else { $page = 1; } // Variables $row = 0; $images_per_page = 10; // How many images to display on each page $images = get_field( ‘image_gallery’ ); $total = count( $images ); $pages = ceil( $total / $images_per_page ); $min = ( ( $page * $images_per_page ) $images_per_page ) + 1; $max = ( $min + $images_per_page ) 1; // ACF Loop if( have_rows( ‘image_gallery’ ) ) : ?> while( have_rows( ‘image_gallery’ ) ): the_row(); $row++; // Ignore this image if $row is lower than $min if($row < $min) { continue; } // Stop loop completely if $row is higher than $max if($row > $max) { break; } ?> $img_obj = get_sub_field( ‘image’ ); ?> <a href= echo $img_obj[‘sizes’][‘large’]; ?>> <img src= echo $img_obj[‘sizes’][‘thumbnail’]; ?> alt=> a> endwhile; // Pagination echo paginate_links( array( ‘base’ => get_permalink() .%#%’ . ‘/’, ‘format’ =>?page=%#%’, ‘current’ => $page, ‘total’ => $pages ) ); ?> else: ?> No images found endif; ?>

[/php]

A note about Custom Post Types

This technique will also work on Custom Post Type single templates. Your pagination permalinks will have the format /post-type/post-slug/2/.

Credits

My solution was inspired by Elliot Condon and Twansparent’s contributions to the Advanced Custom Fields forum.

How to Beautifully Formatted Archives by Month Separated by Year

Are you looking for a way to display a beautifully formatted archives list of months separated by year? While there’s probably a plugin for this, we have created a quick code snippet that you can use to display formatted archives by month separated by year in WordPress.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

functionwp_custom_archive($args= '') {
    global$wpdb, $wp_locale;
    $defaults= array(
        'limit'=> '',
        'format'=> 'html', 'before'=> '',
        'after'=> '', 'show_post_count'=> false,
        'echo'=> 1
    );
    $r= wp_parse_args( $args, $defaults);
    extract( $r, EXTR_SKIP );
    if( ''!= $limit) {
        $limit= absint($limit);
        $limit= ' LIMIT '.$limit;
    }
    // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
    $archive_date_format_over_ride= 0;
    // options for daily archive (only if you over-ride the general date format)
    $archive_day_date_format= 'Y/m/d';
    // options for weekly archive (only if you over-ride the general date format)
    $archive_week_start_date_format= 'Y/m/d';
    $archive_week_end_date_format= 'Y/m/d';
    if( !$archive_date_format_over_ride) {
        $archive_day_date_format= get_option('date_format');
        $archive_week_start_date_format= get_option('date_format');
        $archive_week_end_date_format= get_option('date_format');
    }
    //filters
    $where= apply_filters('customarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r);
    $join= apply_filters('customarchives_join', "", $r);

    $output= '

;

        $query= "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC $limit";
        $key= md5($query);
        $cache= wp_cache_get( 'wp_custom_archive', 'general');
        if( !isset( $cache[ $key] ) ) {
            $arcresults= $wpdb->get_results($query);
            $cache[ $key] = $arcresults;
            wp_cache_set( 'wp_custom_archive', $cache, 'general');
        } else{
            $arcresults= $cache[ $key];
        }
        if( $arcresults) {
            $afterafter= $after;
            foreach( (array) $arcresultsas$arcresult) {
                $url= get_month_link( $arcresult->year, $arcresult->month );
                /* translators: 1: month name, 2: 4-digit year */
                $text= sprintf(__('%s'), $wp_locale->get_month($arcresult->month));

                $year_text= sprintf('

  • %d

, $arcresult->year);

                if( $show_post_count)
                    $after= ' ('.$arcresult->posts.')'. $afterafter;
                $output.= ( $arcresult->year != $temp_year) ? $year_text: '';
                $output.= get_archives_link($url, $text, $format, $before, $after);
                $temp_year= $arcresult->year;
            }
        }

    $output.= '

;

    if( $echo)
        echo$output;
    else
        return$output;
}
Add this snippet in your index.php file or any other template file where you want to display the formatted archives.

WordPress Enqueue Custom Fonts

/** Custom Fonts

function enqueue_custom_fonts(){
if (!is_admin()) {
wp_register_style(‘source_sans_pro’, ‘https://fonst.googleapis.com/’):
wp_register_style(‘nunito’, ‘https://fonst.google.com/’);

wp_enqueue_style(‘source_sans_pro’);
wp_enqueue_style(‘nunito’);

}

}
add_action (‘wp_enqueue_scripts’, ‘enqueue_custom_fonts’);

Protect your WordPress by hiding the REST API

The WordPress REST API was introduced in the WordPress core at the end of 2016 with the release of WordPress 4.6. Like all the big changes that appear in the platform, the REST API generated controversy in some and indifference in others.

It’s even possible that you have no idea what it is, but if you have an updated version of WordPress (and you should) you are exposing many aspects of your website publicly through the REST API. Just append the fragment /wp-json/ to your domain name and visit this URL to see it with your own eyes.

Moreover, do the exercise of visiting the following web URLs and you may be surprised with what you’ll find:

  • mydomain.com/wp-json/wp/v2/users
  • mydomain.com/wp-json/wp/v2/posts

As a result of the first URL you will have a JSON with the data of the users of your web. Notice that user identifiers are included there, and this is something that people traditionally hide due to security issues and to prevent possible attacks.

The second URL shows us a list with the last posts. However, if you have protected content that only certain premium users of your website (in a membership site, for example) should have access to, it’s possible that you’ve been exposing this premium content through the REST API.

Let’s see how we can avoid compromised situations by being more aware of what we publicly expose through the WordPress REST API.

Show WordPress REST API Only to Registered Users

A solution that we can implement to hide the WordPress REST API is to prevent those users who are not registered on our website from accessing it.

To hide the REST API to unregistered users, we must add the following code in our WordPress. Remember that you can put it in the functions.php file of your theme or just develop a plugin for it (a much better option).


}
if ( ! current_user_can( 'administrator' ) ) {
return new WP_Error( 'rest_not_admin', 'You are not an administrator.', array( 'status' => 401 ) );
}
return $result;
});


}
return $result;
});

A Simple Template for Post Formats



>
’;
echo the_title();
echo ‘

’;
echo the_content();
}
elseif ( has_post_format( ‘gallery’ )) {
echo ‘

’;
echo the_title();
echo ‘

’;
echo the_content();
}

elseif ( has_post_format( ‘image’ )) {
echo ‘

’; echo the_title(); echo ‘

’; echo the_post_thumbnail(‘image-format’); echo the_content();}
elseif ( has_post_format( ‘link’ )) {
echo ‘

’; echo the_title(); echo ‘

’; echo the_content();}
elseif ( has_post_format( ‘quote’ )) {
echo the_content();}
elseif ( has_post_format( ‘status’ )) {
echo the_content();}
elseif ( has_post_format( ‘video’ )) {
echo ‘

’; echo the_title(); echo ‘

’; echo the_content();}
elseif ( has_post_format( ‘audio’ )) {
echo ‘

’; echo the_title(); echo ‘

’; echo the_content();}
else {
echo ‘

’; echo the_title(); echo ‘

’; echo the_content();}
?>




Hide all WordPress update notifications in dashboard

WordPress has a build-in upgrade system. This system automatically informs you when there is an upgrade available for WordPress, or one of the themes or plugins that are installed on your WordPress installation.

To disable this update notification, there is no switch in the settings menu or anywhere else in the admin dashboard. To prevent WordPress from showing these information snippets on top of your WordPress dashboard, you shall need to add a PHP code snippet to your functions.php file.

So head over to your theme’s folder (/wp-content/themes/your-theme) and open the functions.php file.

Now past the following code at the bottom of that file:

Disable WordPress update notification
1
2
3
4
5
6
7
// hide update notifications
function remove_core_updates(){
global $wp_version;return(object) array('last_checked'=> time(),'version_checked'=> $wp_version,);
}
add_filter('pre_site_transient_update_core','remove_core_updates'); //hide updates for WordPress itself
add_filter('pre_site_transient_update_plugins','remove_core_updates'); //hide updates for all plugins
add_filter('pre_site_transient_update_themes','remove_core_updates'); //hide updates for all themes

Remove any of the last three lines if you only want to hide core updates, themes updates or plugin updates.

Save your file and the update notification in your WordPress admin area should be gone. If you work with clients, this may be an elegant solution for you to keep the interface of your client’s dashboard as simple as possible.

Free Web Hosting