Say you want to use the featured image (post thumbnail) that WordPress provides, but you have an archive with many posts and it would take a long time to add that featured image to each of them.
For new posts you can use the featured image in the standard way, but for old posts you want to use the first image in the post content as the featured image, or a default image if there are no images in that specific post. Add the following code to functions.php:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+?src=['"]([^'"]+)['"].*?>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
if(empty($first_img)) {
$first_img = "/path/to/default.png";
}
return $first_img;
}
And to use this inside the WordPress loop:
if ( get_the_post_thumbnail($post_id) != '' ) {
echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
the_post_thumbnail();
echo '</a>';
} else {
echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
echo '<img src="';
echo catch_that_image();
echo '" alt="" />';
echo '</a>';
}
For more on WordPress image handling, see Image Sizes in WordPress.
The body_class function helps add classes to the body tag, which usually contains information about what type of page is currently displayed, and allows you to style specific elements on that page by that specific class.
For some reason WordPress does not add a class describing which category (or categories) you are in on a single post page (e.g. single.php). To add the category name to that body tag, use the following code:
function sv_add_category_to_single($classes) {
if (is_single() ) {
global $post;
foreach((get_the_category($post->ID)) as $category) {
// add category slug to the $classes array
$classes[] = $category->category_nicename;
}
}
// return the $classes array
return $classes;
}
add_filter('body_class','sv_add_category_to_single');
This uses the body_class filter. Learn more in WordPress Hooks Explained.
To enable thumbnails or featured images in posts, all you need to do is add the following line to your theme’s functions.php file:
add_theme_support('post-thumbnails');
It is also simple to display this image as HTML that produces the desired <img> tag:
get_the_post_thumbnail();
But what if you need only the URL of that featured image? Say when you want to use it as background-image on a specific element. It is not as simple as you might expect, but not that complicated either. What you need to do is add the following code inside the WordPress loop:
The variable $thumb_url will contain the URL of the featured image of the post in question…
For more on featured images and thumbnails, see Image Sizes in WordPress.
The following code displays in the footer the number of database queries the page executed, the time it took to run those queries, and the memory usage of the page.
function sv_performance( $visible = false ) {
$stat = sprintf( '%d queries in %.3f seconds, using %.2fMB memory',
get_num_queries(),
timer_stop( 0, 3 ),
memory_get_peak_usage() / 1024 / 1024
);
echo $visible ? $stat : "<!-- {$stat} -->" ;
}
add_action( 'wp_footer', 'sv_performance', 20 );
The result appears as a comment in the footer. Check the page source to see it:
<!-- 33 queries in 1.532 seconds, using 48.75MB memory -->
For more performance optimization, see Improve WordPress Loading Time.
Add the following code to your functions.php file to add your own fields to the user profile page in the WordPress admin.
// CUSTOM USER PROFILE FIELDS
function my_custom_userfields( $contactMethods ) {
// ADD CONTACT CUSTOM FIELDS
$contactMethods['contact_phone_office'] = 'Office Phone';
$contactMethods['contact_phone_mobile'] = 'Mobile Phone';
$contactMethods['contact_office_fax'] = 'Office Fax';
// ADD ADDRESS CUSTOM FIELDS
$contactMethods['address_line_1'] = 'Address Line 1';
$contactMethods['address_line_2'] = 'Address Line 2 (optional)';
$contactMethods['address_city'] = 'City';
$contactMethods['address_state'] = 'State';
$contactMethods['address_zipcode'] = 'Zipcode';
}
add_filter('user_contactmethods','my_custom_userfields',10,1);
To display these fields you can use one of the following methods:
the_author_meta('facebook', $current_author->ID)
<?php $current_author = get_userdata(get_query_var('author')); ?>
<p><a href="<?php echo esc_url($current_author->contact_phone_office);?>" title="office_phone"> Office Phone</a></p>
For a more robust approach to custom fields, see Beginner’s Guide to Advanced Custom Fields.
The following code adds a new widget to the WordPress Dashboard. You can of course set what content appears in this widget. Add this code to your theme’s functions.php file:
add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');
function my_custom_dashboard_widgets() {
wp_add_dashboard_widget('custom_help_widget', 'Help and Support', 'custom_dashboard_help');
}
function custom_dashboard_help() {
echo '<p>Lorum ipsum delor sit amet et nunc</p>';
}
It looks like this:
%22%20transform%3D%22translate(2%202)%20scale(3.98828)%22%20fill-opacity%3D%22.5%22%3E%3Cellipse%20fill%3D%22%23d0d0d0%22%20rx%3D%221%22%20ry%3D%221%22%20transform%3D%22matrix(40.34734%20-12.14879%2027.26829%2090.56075%20111.6%20167.7)%22%2F%3E%3Cellipse%20fill%3D%22%23d1d1d1%22%20rx%3D%221%22%20ry%3D%221%22%20transform%3D%22rotate(-42.4%20296.6%20-197.4)%20scale(66.62459%2027.53765)%22%2F%3E%3Cellipse%20fill%3D%22%23fff%22%20cx%3D%2294%22%20rx%3D%22137%22%20ry%3D%22137%22%2F%3E%3Cellipse%20fill%3D%22%23d1d1d1%22%20rx%3D%221%22%20ry%3D%221%22%20transform%3D%22rotate(-137.3%2069.8%2037.5)%20scale(32.19295%2038.92402)%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E)
For safe theme customizations, see What Are Child Themes and How to Use Them.
I want to delay publishing to the RSS feed by 10-15 minutes because I always find a few errors after publishing. Another scenario is when you want your site content to be exclusive for a while and not appear in the RSS feed.
// Delay feed update
function publish_later_on_feed($where) {
global $wpdb;
if (is_feed()) {
// Timestamp in WordPress format
$now = gmdate('Y-m-d H:i:s');
// Value for wait; + device
$wait = '10'; // integer
// http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff
$device = 'MINUTE'; // MINUTE, HOUR, DAY, WEEK, MONTH, YEAR
// Add SQL syntax to default $where
$where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";
}
return $where;
}
add_filter('posts_where', 'publish_later_on_feed');
For more RSS management, see Disable RSS Feeds in WordPress.
To add Custom Post Types to the site’s main RSS feed by default, add the following code to your theme’s functions.php file:
// ADD CUSTOM POST TYPES TO THE DEFAULT RSS FEED
function custom_feed_request( $vars ) {
if (isset($vars['feed']) && !isset($vars['post_type']))
$vars['post_type'] = array( 'post', 'site', 'plugin', 'theme', 'person' );
return $vars;
}
add_filter( 'request', 'custom_feed_request' );
When you upload an image using WordPress media and then insert it into the content editor, the image is attached with width and height attributes. These attributes are generally desirable because they help the browser reserve the right space for the image during layout.
But if you want to prevent WordPress from adding these width and height attributes, add the following code to your theme’s functions.php file:
add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );
function remove_width_attribute( $html ) {
$html = preg_replace( '/(width|height)="d*"s/', "", $html );
return $html;
}
Here is a simple way to redirect a user to a specific page when they remove a WooCommerce coupon from the cart page. Useful for example if you want to show content to users who remove a coupon that was automatically added to the cart. Here is how:
/*
* Redirects user to a specific page upon coupon removal.
*/
function action_woocommerce_removed_coupon( $coupon_code ) {
// Redirection...
wp_redirect( $url ); // Replace $url by your page URL.
exit;
};
// add the action
add_action( 'woocommerce_removed_coupon', 'action_woocommerce_removed_coupon', 10, 1 );