Images in radio / checkboxes

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:

<script>
  
  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;
	label.appendChild(img);
});
  
</script>
1 Like