If you want to enrich your WordPress product categories with custom URLs, follow these steps to seamlessly integrate a custom URL field on both the ‘Add New Term’ and ‘Edit Term’ pages:
Add Term Page:
function custom_url_taxonomy_add_new_meta_field() {
?>
<div class="form-field">
<label for="term_meta[custom_term_meta]"><?php _e( 'Custom URL Category', 'custom_url_category' ); ?></label>
<input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="">
<p class="description"><?php _e( 'Insert a custom URL for the category','custom_url_category' ); ?></p>
</div>
<?php
}
add_action( 'product_cat_add_form_fields', 'custom_url_taxonomy_add_new_meta_field', 10, 2 );
Edit Term Page:
function custom_url_taxonomy_edit_meta_field($term) {
$t_id = $term->term_id;
$term_meta = get_option( "taxonomy_$t_id" );
?>
<tr class="form-field">
<th scope="row" valign="top"><label for="term_meta[custom_term_meta]"><?php _e( 'Custom URL Category', 'custom_url_category' ); ?></label></th>
<td>
<input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="<?php echo esc_attr( $term_meta['custom_term_meta'] ) ? esc_attr( $term_meta['custom_term_meta'] ) : ''; ?>">
<p class="description"><?php _e( 'Insert a custom URL for the category','custom_url_category' ); ?></p>
</td>
</tr>
<?php
}
add_action( 'product_cat_edit_form_fields', 'custom_url_taxonomy_edit_meta_field', 10, 2 );
Save Extra Taxonomy Fields:
function save_taxonomy_custom_meta( $term_id ) {
if ( isset( $_POST['term_meta'] ) ) {
$t_id = $term_id;
$term_meta = get_option( "taxonomy_$t_id" );
$cat_keys = array_keys( $_POST['term_meta'] );
foreach ( $cat_keys as $key ) {
if ( isset ( $_POST['term_meta'][$key] ) ) {
$term_meta[$key] = $_POST['term_meta'][$key];
}
}
update_option( "taxonomy_$t_id", $term_meta );
}
}
add_action( 'edited_product_cat', 'save_taxonomy_custom_meta', 10, 2 );
add_action( 'create_product_cat', 'save_taxonomy_custom_meta', 10, 2 );
This set of functions facilitates the addition, editing, and saving of custom URLs for WordPress product categories. Simply integrate this code into your theme’s functions.php file or create a custom plugin for an enhanced and organized approach. Now, you can effortlessly manage custom URLs for your product categories directly from the WordPress admin interface.
Leave a Reply