Develop a custom WordPress meta box for managing the color scheme of individual posts and pages

Currently, I am in the process of learning how to create a custom WordPress meta box with a select tag for controlling the color scheme of individual posts/pages. My goal is to implement a system where I can use if statements to load an additional CSS file that will override the original CSS file colors using the wp_enqueue_style function in functions.php.

Thus far, I have utilized the code provided by the WordPress codex for adding the meta box and displaying the value from get_post_meta. The code is currently integrated as a plugin.

For the Meta Box Code, refer to: http://codex.wordpress.org/Function_Reference/add_meta_box

<?php

/**
 * Adds a box to the main column on the Post and Page edit screens.
 */
function myplugin_add_meta_box() {

$screens = array( 'post', 'page' );

foreach ( $screens as $screen ) {

add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_meta_box_callback',
$screen
);
}
}
add_action( 'add_meta_boxes', 'myplugin_add_meta_box' );

/**
 * Prints the box content.
 * 
 * @param WP_Post $post The object for the current post/page.
 */
function myplugin_meta_box_callback( $post ) {

// Add a nonce field for security checks.
wp_nonce_field( 'myplugin_meta_box', 'myplugin_meta_box_nonce' );

/*
 * Use get_post_meta() to fetch an existing value
 * from the database and populate the form.
 */
$value = get_post_meta( $post->ID, '_my_meta_value_key', true );

echo '<label for="myplugin_new_field">';
_e( 'Description for this field', 'myplugin_textdomain' );
echo '</label> ';
echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="' . esc_attr( $value ) . '" size="25" />';
}

/**
 * Handles saving custom data when the post is saved.
 *
 * @param int $post_id The ID of the post being saved.
 */
function myplugin_save_meta_box_data( $post_id ) {

// Check if our nonce is set.
if ( ! isset( $_POST['myplugin_meta_box_nonce'] ) ) {
return;
}

// Verify the validity of the nonce.
if ( ! wp_verify_nonce( $_POST['myplugin_meta_box_nonce'], 'myplugin_meta_box' ) ) {
return;
}

// Avoid autosave triggers.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}

// Check user permissions.
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {

if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}

} else {

if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
}

// Data can now be safely saved.

if ( ! isset( $_POST['myplugin_new_field'] ) ) {
return;
}

$my_data = sanitize_text_field( $_POST['myplugin_new_field'] );

update_post_meta( $post_id, '_my_meta_value_key', $my_data );
}
add_action( 'save_post', 'myplugin_save_meta_box_data' );

For Value Output, visit: http://codex.wordpress.org/Function_Reference/get_post_meta

<?php 
$my_data = get_post_meta( $post->ID, '_my_meta_value_key', true );
// Verify if the custom field has a value
if( ! empty( $my_data ) ) {
  echo $my_data;
} 
?>

I am currently facing challenges in understanding how to modify the code logic if I choose to replace the input tag with a select tag containing color options that will determine which CSS file to utilize for overriding the original file.

Many thanks for your assistance!

Update

Following the advice provided by patnz, I have updated the value output as follows and successfully implemented it. I will now proceed to integrate this into my theme. Thank you!

<?php 
$my_data = get_post_meta( $post->ID, '_my_meta_value_key', true );
// Check if the custom field has a value
if( $my_data == val1 ) {
  echo $my_data;
} elseif ($my_data == val2) {
  echo $my_data;
}
?>

Answer №1

If everything is functioning correctly up to this point and you're looking to swap out the input[type=text] with a select, your select element will appear as shown below:

//... continuation of the code above

// SIMPLY REMOVE INPUT TAG - // echo '<input type="text" id="myplugin_new_field"...

 echo '<select id="myplugin_new_field" name="myplugin_new_field">';
 echo '<option value="">- Select a value -</option>';
 echo '<option value="val1" '.selected("val1",esc_attr( $value )).'" >Value 1</option>';
 echo '<option value="val2" '.selected("val2",esc_attr( $value )).'" >Value 2</option>';
 echo '</select>';
  • The selected() function in WordPress compares two values and includes the selected attribute in the option tag if the values match.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to ensure that the question text will wrap onto a new line if it becomes too lengthy

I am currently working on developing ASP.NET MVC applications. However, I am facing a design issue with the HTML, CSS, and Bootstrap elements on one of my pages. The problem arises when Question 8 exceeds the border and does not wrap to a new line as inte ...

Creating a responsive design using Bootstrap4

Today, I made the switch to bootstrap4 and enabled flexbox in _variables.scss. However, I'm still confused about the flexbox capabilities of bootstrap4. Some questions I have include: How can I utilize flex-direction:column? Is it possible to creat ...

When the filter feGaussianBlur is applied to an SVG circle, it disappears on Safari but not on Chrome

While implementing the filter with feGaussianBlur to an SVG circle, I encountered a peculiar issue. It works perfectly on Chrome, but unfortunately, the circle disappears when viewed on Safari. https://i.sstatic.net/k916B.png https://i.sstatic.net/5Bfp9. ...

Tips for creating a responsive background image without excessive scaling:

I'm currently working on a website with a focus on responsibility, and I've incorporated 'waves' SVG images as a background-image. The issue arises when viewing the site on smaller screens, such as mobile devices, where the background a ...

Is there a way to reverse the animation playback in Angular?

I am working on an animation that involves a box fading from its original color to yellow. However, I would like to achieve the opposite effect: when the page loads, I want the box to start off as yellow and then fade back to its original color. The challe ...

I'm looking to have a span and an input side by side, both spanning the full width of the containing div. How can I achieve this?

In my code snippet below: <html> <body> <div style="width: 700px;"> <span>test</span> <input style="width: 100%;"></input> </div> </body> </html> I am facing an issue where the span and input el ...

The element will only show up upon resizing (in Safari web browser)

I am facing a problem with a button styled using the class btn-getInfo-Ok <button class="btn-getInfo-Ok">Hello</button> in my style.css file .btn-getInfo-Ok { color:white !important; margin: 0 auto !important; height:50px; bottom:0; ...

Enhancing Your Website with Multiple Background Images in CSS3

Having trouble understanding how to position multiple background images with CSS3. I'm struggling to get them to display at the top, middle, and bottom of the page. Can you help me figure out how to make an image appear at different positions using a ...

How can I add color to arrow icons in tabulator group rows?

Is there a way to specify the color of the arrows in collapsed/expanded group rows? Also, what CSS code should I use to define the font color for column group summaries? You can view an example of what I am trying to customize here: https://jsfiddle.net/s ...

Aligning Text at the Center in Your React Native Application

I'm facing a few issues with my visualization: Despite aligning it to the center, the text on my first button is positioned at the right end of the button. How can I move the text 'login' to the center? Currently, the 'Sign Up Her ...

Is there a way to extract shared properties within a Material UI style declaration?

I am working with a specific set of style rules that define different statuses: status_in_progress: { fontSize: 14, backgroundColor: theme.palette.success.dark, padding: 2, paddingLeft: 5, paddingRight: 5, display: "inline-bl ...

Using jQuery, locate identical text and assign a class to the corresponding container

How can I check if any of the h2 elements match the text in h1, ignoring case sensitivity? If a match is found, I want to add a class to the container Product-div. <div id="PageHeader"> <h1>Same text</h1> </div> <div class= ...

How can I show a view page in a specific div element using CodeIgniter?

Here is how I'm implementing the dashboard view in my controller. My goal is to have a specific page, like the index page, displayed within a div element rather than opening in a new tab. public function index() { $this->load->view('in ...

I am required to filter out any child elements from a find() operation

HTML: <ul> <li class="listExpandTrigger"><h3>2010 - present</h3></li> <li class="listCollapseTrigger"><h3>2010 - present</h3></li> <li> <ul class="volumeList"> <l ...

Switching the horizontal tab design from Bootstrap 3 to Bootstrap 4

I'm currently working on adapting a code snippet from bootsnip that creates horizontal Bootstrap tabs with material-style design. I've encountered some challenges in converting it to Bootstrap 4, specifically in updating the CSS to use .nav-item ...

What is the correct way to customize colors for specific components in Material-ui?

Struggling with theming in Material-UI, particularly when it comes to customizing element colors. Some elements default to 'theme.palette.main.dark' and I want to override this behavior. For example, the TextField and SpeedDial components automa ...

The Angular overlay is concealed beneath the pinned header

I am seeking a solution to have a mat-spinner displayed on top of my app while it is in the loading state. Currently, I am using an overlay component with Overlay from @angular/cdk/overlay. The issue arises when part of the spinner that should be overlai ...

The wget tool is capable of downloading CSS files that contain @import rules, however it overlooks

Currently utilizing the following command with wget: wget --page-requisites --convert-links -e robots=off \ --span-hosts --restrict-file-names=windows \ --directory-prefix=$ASSETS_DIR --no-directories http://myhost/home The HTML page ...

What is the best way to initiate a slideshow using an external .js file?

Having an issue with my slideshow. When I put the CSS and JavaScript code in the same page, it kind of "works" but quickly goes transparent, which is not ideal for me. I prefer keeping things organized with separate files - one for each. However, when I mo ...

Automatically adjusting jQuery script now functions on all hyperlinks for seamless resizing

I am attempting to create a rollover script that will resize my social network links when hovered over. The desired effect is for the 32px square icon to expand and display the trailing address. For example, when hovering over the Facebook link, it should ...