Add custom image sizes, the right way

Since version 2.9, WordPress supports custom image sizes that will be used to create thumbnails of image attachments. Adding new image sizes is pretty easy; in your theme’s functions.php file, add this block of code:

function mytheme_add_image_sizes() {
    add_image_size( 'small_thumb', 50, 50, true );
}
add_action( 'after_setup_theme', 'mytheme_add_image_sizes' );

… and you’re done. Now, everytime a new image is uploaded, a 50×50 thumbnail with be created for you.

However, this new image size won’t show up when you want to insert an image into a post:

Image size dropdown on Insert Media frame

Image size dropdown on Insert Media frame

The solution is pretty simple too; add this bit of code into your theme’s functions.php file:

function mytheme_image_size_names( $sizes ) {
    $sizes['small_thumb'] = __( 'Small Thumb', 'mytheme' );

    return $sizes;
}
add_filter( 'image_size_names_choose', 'mytheme_image_size_names' );

Now you can select your custom image size from the dropdown:

Image size dropdown on Insert Media frame, with custom image sizes.

Image size dropdown on Insert Media frame, with custom image sizes.

Notes:

Standard

5:45am

#snowNOT

All photos in this gallery are released under GPL v2. Attribution would be greatly appreciated.

Gallery

Additional Fields for Soliloquy Images

So… I was asked to convert an HTML template into a a WordPress page template, and it has two sliders. A friend of mine recommended me to use Soliloquy, which is a very nice plugin. However, since I didn’t want to mess with the markup and styling, I opted to only use Soliloquy’s backend.

Now, the markup contains an additional text which is not suitable for the existing image fields (title, alt, caption, etc), so I needed to add an additional field to the image meta frame, and here’s how I did it:

/**
 * Add extra custom fields to slideshow images
 */
function _my_soliloquy_slide_source_field( $id, $data, $post_id ) {
	$source = ! empty( $data['source'] ) ? $data['source'] : '';
	?>
		<tr id="soliloquy-source-box-<?php echo esc_attr( $id ) ?>" valign="middle">
			<th scope="row"><label for="soliloquy-source-<?php echo esc_attr( $id ) ?>"><?php _e( 'Source', 'mytheme' ); ?></label></th>
			<td>
				<input id="soliloquy-source-<?php echo esc_attr( $id ) ?>" class="soliloquy-source" type="text" name="_soliloquy[meta_source]" value="<?php echo esc_attr( $source ); ?>" data-soliloquy-meta="source" />
			</td>
		</tr>
	<?php
}
add_action( 'soliloquy_after_image_meta_settings', '_my_soliloquy_slide_source_field', 1, 3 );


/**
 * Save slideshow images's extra custom fields
 */
function _my_soliloquy_ajax_save_meta( $slider_data, $meta, $attach_id, $post_id ) {
	if ( ! empty( $meta['source'] ) ) {
		$slider_data['slider'][ $attach_id ]['source'] = sanitize_text_field( $meta['source'] );
	}
	else {
		unset( $slider_data['slider'][ $attach_id ]['source'] );
	}

	return $slider_data;
}
add_action( 'soliloquy_ajax_save_meta', '_my_soliloquy_ajax_save_meta', 10, 4 );

_sol_slider_data now contains the source field’s value.

Standard

Custom byline markup for Co-Authors Plus

Co-Authors Plus is a nice plugin for assigning multiple authors to posts. However, I find its template tag for displaying byline rather limiting because sometimes we want to use fancy markup for the byline (think of avatars, publish/modification dates, etc). You can use the code below as the base for your theme’s byline markup (in this example, we’re overriding twentyfourteen_posted_on()):

function twentyfourteen_posted_on() {
	if ( is_sticky() && is_home() && ! is_paged() ) {
		echo '<span class="featured-post">' . __( 'Sticky', 'twentyfourteen' ) . '</span>';
	}

	// Set up and print post meta information.
	printf( '<span class="entry-date"><a href="%1$s" rel="bookmark"><time class="entry-date" datetime="%2$s">%3$s</time></a></span>',
		esc_url( get_permalink() ),
		esc_attr( get_the_date( 'c' ) ),
		esc_html( get_the_date() )
	);

	// get the co-authors
	if ( function_exists( 'get_coauthors' ) ) {
		$authors = get_coauthors();
	}

	// Fallback to WP users
	if ( empty( $authors ) || ! is_array( $authors ) ) {
		$authors = array( get_userdata( get_the_author_meta( 'ID' ) ) );
	}

	foreach ( $authors as $author ) {
		$_args = apply_filters(
			'coauthors_posts_link',
			array( 'href' => get_author_posts_url( intval( $author->ID ), $author->user_nicename ) )
		);

		printf(
			'<span class="byline"><span class="author vcard"><a class="url fn n" href="%1$s" rel="author">%2$s</a></span></span>',
			esc_url( $_args['href'] ),
			esc_html( $author->display_name )
		);
	}
}

“So how do I display the avatars” you ask? Add the following code to your theme’s functions.php file and use it to get the avatar image instead of the default get_avatar():

/**
 * Wrapper for get_avatar
 *
 * @param mixed  $user    User object, ID or email
 * @param int    $size    Avatar size
 * @param string $default Default avatar image
 * @param string $alt     Alt text
 */
function kucrut_get_avatar( $user, $size = 33, $default = '', $alt = false ) {
	if ( is_object( $user ) && function_exists( 'coauthors_get_avatar' ) ) {
		return coauthors_get_avatar( $user, $size, $default, $alt );
	}
	else {
		return get_avatar( $user, $size, $default, $alt );
	}
}
Standard

The State of Bluetooth Headset in Linux

A few days ago, I bought a shiny Sony SBH80 bluetooth headset. This is my first bluetooth headset ever, so I thought I’d share my experience in setting it up.

Android

Yes, Android is Linux, just not the regular one 🙂
I have a Nexus 5 phone and since it comes with KitKat, the headset is fully supported. Audio quality is superb (both for streaming music and making calls). The only annoyance I experienced is that the headset need to be disconnected from the phone first before connecting it with PC. When the connection with the PC is established, you can then reconnect it with the phone (yes, it supports multiple connections).

Gentoo

I’m running the unstable Gentoo Linux, so I always have the (relatively) latest packages available. I have BlueDevil 2.0_rc1 installed as part of my KDE desktop, along with BlueZ 5.18 as its dependency. BlueDevil easily established the connection with the headset but I couldn’t use it as audio output/sink.

After a quick research, I found out that BlueZ needs to have PulseAudio support to make use of the headset functionalities. I then rebuilt it (along with some multimedia packages) with PulseAudio support. After logging in back to KDE, the headset worked. All I needed to do was giving the headset the highest priority in KDE Phonon settings, so when it’s available, Phonon will use that as the output, otherwise it will revert back to the other available devices.

However, I couldn’t make the microphone work. After some digging, I found out that HSP & HFP support were removed from Bluez 5.0, so until oFono provide those profiles, there’s no way to use the microphone 🙁

I was curious and downgraded BlueDevil, Bluez and some other packages to their previous versions that support HFP & HSP profiles. I also removed PulseAudio support from my system since it’s not required. I had to add the following lines to /etc/asound.conf to make the headset recognized by ALSA:

pcm.sbh80 {
        type plug
        slave {
                pcm {
                        type bluetooth
                        device xx:xx:xx:xx:xx:xx
                        profile "auto"
                }
        }
        hint {
                show on
                description "Sony SBH80"
        }
}

ctl.sbh80 {
        type bluetooth
}

After that, the headset worked as audio sink but the microphone was not working still. I then found out that to make use of the microphone, the audio sink service need to be disabled. Enabling only the HFP/HSP profile without A2DP profile with BlueDevil wasn’t possible, so I installed BlueMan and it worked!

However, the sound quality was terrible and often times, Phonon won’t switch to the headset when it’s availabe, and won’t revert back to the built-in sound card when it’s disconnected. Ouch!

I figured, if I added PulseAudio support, the switching should be smooth, and I did. For the most part, it worked, but there’s this delay when the system is making an event sound which was really annoying.

Finally, I reverted back to Bluez5 with PulseAudio support and ‘sacrificed’ the microphone (I don’t do audio chat that often and my built-in mic is working fine anyway). It’s not what I really wanted, but it’s the best option I got and I’m quite happy with it.

Standard

WordPress Plugins Localization

A few days ago, I created an Indonesian translation for the Stream plugin. It’s been a while since I used POEdit to create/update translations, so this post will serve as a reminder for me. 🙂

Before creating the translation for the Stream plugin, I needed to make some changes to the translatable strings so that translators can freely place the tokens. As we all know, each language has its own style, structure, and whatnot, so forcing the order of words in a sentence is a bad idea.

Stream already has some translation when I made those changes, so I needed to provide a quick guide for the translators on how they can update their translations, in this particular case, using POEdit.

Plugin Developers

As plugin developers, you need to read the excellent Language Packs 101 – Prepwork article by Otto, and that’s it. You don’t even need to provide the .po file, but providing the .pot file is a must!

Translators

If this is your first time creating the translation:

  1. Fire up POEdit
  2. Click File » New Catalog From POT file
  3. Select the .pot file provided by the plugin
  4. Fill Up the Translation Properties then click OK
  5. Save the file with this format: <plugin-slug>-<language-code>.po, eg: stream-id_ID.po
  6. Translate away and save the file.

If you already have the translation and want to update it:

  1. Fire up POEdit
  2. Open the current .po file
  3. Click Catalog » Update from POT file
  4. Select the .pot file provided by the plugin
  5. Translate away and save the file.
Standard

Widget Attributes

A while ago, I wrote about how you can add custom classes to your widgets. I’ve also created a plugin that’s available in WPORG but haven’t been updated in a while.

I’m announcing a new plugin, Widget Attributes, that you can use to add custom attributes to your widgets. Currently, it only supports the ID and classes and maybe will support adding custom attributes in the future. For now, you can download it from here. I’m submitting this plugin to WPORG and will retire the old one (I don’t like the name) and will update this post once it’s approved.

Update
The plugin is now live!

Standard