The Text Preview plugin allows you to add a colour picker field so that the user can choose a colour. However, you might want to limit the number of colour options you want to give to the user.
To do this, you’ll need to add a snippet:
<?php | |
/** | |
* Set text preview field to specific colours | |
*/ | |
function prefix_set_preview_colours() { | |
?> | |
<script> | |
jQuery( document ).ready( function( $ ) { | |
var colours = { | |
blue: "0000ff", | |
red: "ff0000" | |
} | |
var colour_field_id = 9484; | |
var preview_field_id = 9483; | |
$( '.pewc-field-' + colour_field_id + ' input' ).on( 'change', function( e ) { | |
var colour = $( this ).val(); | |
colour = colour.toLowerCase(); | |
var hex = colours[colour]; | |
$( '.apaou-text-layer-' + preview_field_id ).css( 'color', '#' + hex ); | |
}); | |
}); | |
</script> | |
<?php | |
} | |
add_action( 'wp_footer', 'prefix_set_preview_colours' ); |
Here’s how to add the snippet.
Using this snippet on your site
The snippet requires two fields: a text preview field and a field to give users the colour options. The colour options field could be a radio group, a select field, or an image swatch field.
In the colour options field, list the colours as options, e.g.:
![](jpg/colour-field-1920x676.jpg)
In this example, we’re offering Red and Blue as colour options.
Updating the snippet
Make a note of the text preview field ID and the colour field ID. You can see where to find the IDs in the screenshot below.
![](https://pluginrepublic.com/wp-content/uploads/2021/10/text-preview-colours-1920x732.jpeg)
You’ll need to make some changes to the snippet above for it to work for your site:
- Update line 13 with the ID of your colour field
- Updated line 14 with the ID of your text preview field
You’ll also need to create a list of hex values for the colours in your colour field. Update the list starting at line 10 with a hex value for each of your colours. Note how the list is formatted. Each colour is in lower case and will match the name of the option in your field – so ‘blue’ matches ‘Blue’. The name of the colour is followed by a colon then the hex value in quote marks. At the end of the line, add a comma, then add your next colour option.