Created
February 6, 2024 14:52
-
-
Save andrasguseo/05defee0726eca268f83afd31071774a to your computer and use it in GitHub Desktop.
TEC > Set a target for the event title
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Set a target for the event title. | |
* The code adds a custom field for events where you can select the link target. | |
* A template override for each calendar view is needed where you want this implemented. | |
* | |
* Usage: Add the snippet to your functions.php file or with a plugin like Code Snippets | |
* | |
* @author: Andras Guseo | |
* | |
* Plugins required: The Events Calendar | |
* Created: February 6, 2024 | |
*/ | |
// Add custom field to the post editor screen | |
function add_custom_field_metabox() { | |
add_meta_box( | |
'event_title_target_metabox', | |
'Target', | |
'render_event_title_target_metabox', | |
'tribe_events', | |
'normal', | |
'default' | |
); | |
} | |
// Render the custom field metabox | |
function render_event_title_target_metabox( $post ) { | |
// Retrieve the current value of the custom field | |
$selected_value = get_post_meta( $post->ID, '_event_title_target', true ); | |
// Define your dropdown options | |
$dropdown_options = [ | |
'_parent', | |
'_blank', | |
'_self', | |
'_top', | |
]; | |
// Output the dropdown HTML | |
echo '<label for="event_title_target">Select an option:</label>'; | |
echo '<select name="event_title_target" id="event_title_target">'; | |
echo '<option value="">Select target</option>'; | |
foreach ( $dropdown_options as $option ) { | |
echo '<option value="' . esc_attr( $option ) . '" ' . selected( $selected_value, $option, false ) . '>' . esc_html( $option ) . '</option>'; | |
} | |
echo '</select>'; | |
} | |
// Save the custom field value when the post is saved | |
function save_custom_field_value( $post_id ) { | |
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { | |
return; | |
} | |
if ( isset( $_POST[ 'event_title_target' ] ) ) { | |
update_post_meta( $post_id, '_event_title_target', sanitize_text_field( $_POST[ 'event_title_target' ] ) ); | |
} | |
} | |
// Hook into WordPress | |
add_action( 'add_meta_boxes', 'add_custom_field_metabox' ); | |
add_action( 'save_post', 'save_custom_field_value' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment