Images in radio / checkboxes

I’m trying to show radio options in a form with an image. Basically I’m looping over a cpt and putting that array into the field.

Everything gets stringified so an img tag for example is just output as plain text. I could and probably will just use some js to take out the img tag of the label and re-append it as an img tag but if there was an option to do this natively in the future that’d be awesome :slight_smile:

Right now I can think of 2 types of implementations (mind you I’m not a php guy so this all might be utter non-sense haha)

  1. Allow rendering the labels as html, probably would need be in a pair of extra curly braces or whatever to ensure only hat part is rendered.
  2. Somehow create a filter that’ll allow us to overwrite the option fields html structure

Just in case someone else comes looking for it, here is how I did it (might edit later if I find something to improve). I’d say it’s a medium hacky way haha but anyways:

  1. Get any cpt with title and featured image into an array of options:
function get_gym_options() {
	$posts = get_posts( 'post_type=gym&numberposts=-1' );
	$options = array();
	foreach ( $posts as $post ) {
		$thumb = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
		$title = $post->post_title;
		$options[] = array( 'label' => $title.$thumb['0'], 'value' => $title );
	//Convert the array into a string with the value|label syntax
    $options = implode("\n", array_map(function ($v) {
        return $v['value'] . '|' . $v['label'];
    }, $options));

	return $options;

Get the options into the form using {echo:get_gym_options}

Lastly, in the page code or a code module:

  const regex1 = /(https?:\/\/[^ ]*)/;
  var options = document.querySelectorAll('.options-wrapper li');

options.forEach(function (option, index) {
  const input = option.querySelector('input');
  const label = option.querySelector('label');
  const inputData = input.dataset.label;
  const imageURL = inputData.match(regex1)[0];
  const labelText = inputData.replace(regex1, '');
  label.innerHTML = labelText;
  var img = document.createElement("img");
	img.src = imageURL;
1 Like

Great! Thanks for sharing the code! :blush: