Home / Disable / CCT ID display as name
Duplicate Snippet

Embed Snippet on Your Site

CCT ID display as name

Code Preview
php
<?php
function gt_id_label_map() {
	return array(
		// CCT slug => [ field => target ]
		'cct' => array(
			// 'articles' => array( 'type' => 'term:article-types' ),
		),
		// CPT slug => [ meta_key => target ]  (adds a new admin column)
		'post_type' => array(
			// 'project' => array( 'client_id' => 'post' ),
		),
		// taxonomy slug => [ term_meta_key => target ]  (adds a new admin column)
		'taxonomy' => array(
			// 'category' => array( 'landing_page_id' => 'post' ),
		),
	);
}
/* =====================================================================
 * 2) VALUE PARSING
 * ===================================================================== */
/**
 * Splits any stored value into a list of raw values.
 * Accepts: 20 | "#20" | "20,21" | "20|21" | array | serialized | JSON | checkbox [ 20 => 'true' ].
 */
function gt_parse_values( $value ) {
	if ( is_string( $value ) ) {
		$value = trim( $value );
		if ( '' === $value ) {
			return array();
		}
		$maybe = maybe_unserialize( $value );
		if ( is_array( $maybe ) ) {
			$value = $maybe;
		} elseif ( '[' === $value[0] || '{' === $value[0] ) {
			$json = json_decode( $value, true );
			if ( is_array( $json ) ) {
				$value = $json;
			}
		}
	}
	$values = array();
	if ( is_array( $value ) ) {
		foreach ( $value as $k => $v ) {
			if ( 'true' === $v || true === $v ) {          // JetEngine checkbox format
				$values[] = $k;
			} elseif ( 'false' === $v || false === $v ) {
				continue;
			} elseif ( is_scalar( $v ) ) {
				$values[] = $v;
			}
		}
	} elseif ( is_scalar( $value ) ) {
		$values = preg_split( '/\s*[,|;]\s*/', (string) $value );
	}
	$values = array_map( function ( $v ) {
		return ltrim( trim( (string) $v ), '#' );
	}, $values );
	return array_values( array_unique( array_filter( $values, 'strlen' ) ) );
}
function gt_parse_ids( $value ) {
	$ids = array_filter( gt_parse_values( $value ), function ( $v ) {
		return is_numeric( $v ) && (int) $v > 0;
	} );
	return array_values( array_map( 'absint', $ids ) );
}
/* =====================================================================
 * 3) LABEL RESOLVERS
 * ===================================================================== */
function gt_cct_manager() {
	if ( ! class_exists( '\Jet_Engine\Modules\Custom_Content_Types\Module' ) ) {
		return null;
	}
	return \Jet_Engine\Modules\Custom_Content_Types\Module::instance()->manager;
}
function gt_cct_item_label( $id, $slug, $field = '' ) {
	$manager = gt_cct_manager();
	if ( ! $manager || ! $slug ) {
		return '';
	}
	$type = $manager->get_content_types( $slug );
	if ( ! $type || empty( $type->db ) ) {
		return '';
	}
	$item = $type->db->get_item( $id );
	if ( empty( $item ) ) {
		return '';
	}
	return gt_pick_label( (array) $item, $field );
}
/**
 * Picks a human label from an item array (CCT row, WP_Post, WP_Term, WP_User…).
 */
function gt_pick_label( $item, $field = '' ) {
	if ( $field && isset( $item[ $field ] ) && is_scalar( $item[ $field ] ) && '' !== (string) $item[ $field ] ) {
		return (string) $item[ $field ];
	}
	foreach ( array( 'post_title', 'name', 'title', 'nazov', 'label', 'display_name' ) as $f ) {
		if ( isset( $item[ $f ] ) && is_scalar( $item[ $f ] ) && '' !== (string) $item[ $f ] ) {
			return (string) $item[ $f ];
		}
	}
	return '';
}
function gt_id_to_label( $id, $target ) {
	static $cache = array();
	$key = $target . '|' . $id;
	if ( isset( $cache[ $key ] ) ) {
		return $cache[ $key ];
	}
	$parts = explode( ':', $target );
	$label = '';
	switch ( $parts[0] ) {
		case 'post':
			$post = get_post( $id );
			if ( $post ) {
				$label = '' !== $post->post_title ? $post->post_title : sprintf( '(bez názvu #%d)', $id );
			}
			break;
		case 'term':
			$term = get_term( $id, isset( $parts[1] ) ? $parts[1] : '' );
			if ( $term && ! is_wp_error( $term ) ) {
				$label = $term->name;
			}
			break;
		case 'user':
			$user = get_userdata( $id );
			if ( $user ) {
				$label = $user->display_name;
			}
			break;
		case 'cct':
			$label = gt_cct_item_label(
				$id,
				isset( $parts[1] ) ? $parts[1] : '',
				isset( $parts[2] ) ? $parts[2] : ''
			);
			break;
	}
	return $cache[ $key ] = $label;
}
/* =====================================================================
 * 4) FIELD OPTIONS SOURCE (same labels as the select in the edit form)
 * ===================================================================== */
/**
 * Builds value => label map from a JetEngine field's options source.
 */
function gt_field_options_map( $field ) {
	$map    = array();
	$source = isset( $field['options_source'] ) ? $field['options_source'] : '';
	if ( ! $source ) {
		if ( ! empty( $field['query_id'] ) ) {
			$source = 'query';
		} elseif ( ! empty( $field['options_from_glossary'] ) ) {
			$source = 'glossary';
		}
	}
	try {
		// Query Builder — "Get options from query".
		if ( 'query' === $source && ! empty( $field['query_id'] ) && class_exists( '\Jet_Engine\Query_Builder\Manager' ) ) {
			$query = \Jet_Engine\Query_Builder\Manager::instance()->get_query_by_id( $field['query_id'] );
			if ( $query ) {
				$value_field = ! empty( $field['query_value_field'] ) ? $field['query_value_field'] : '';
				$label_field = ! empty( $field['query_label_field'] ) ? $field['query_label_field'] : '';
				foreach ( (array) $query->get_items() as $item ) {
					$item = is_object( $item ) && method_exists( $item, 'to_array' ) ? $item->to_array() : (array) $item;
					if ( $value_field && isset( $item[ $value_field ] ) ) {
						$value = $item[ $value_field ];
					} else {
						$value = null;
						foreach ( array( '_ID', 'ID', 'term_id' ) as $f ) {
							if ( isset( $item[ $f ] ) ) {
								$value = $item[ $f ];
								break;
							}
						}
					}
					$label = gt_pick_label( $item, $label_field );
					if ( null !== $value && is_scalar( $value ) && '' !== $label ) {
						$map[ (string) $value ] = $label;
					}
				}
			}
		}
		// Glossary.
		if ( 'glossary' === $source && ! empty( $field['glossary_id'] ) && function_exists( 'jet_engine' ) ) {
			$glossaries = jet_engine()->glossaries;
			if ( $glossaries && isset( $glossaries->filters ) && method_exists( $glossaries->filters, 'get_glossary_options' ) ) {
				foreach ( (array) $glossaries->filters->get_glossary_options( $field['glossary_id'] ) as $k => $o ) {
					if ( is_array( $o ) && isset( $o['value'] ) ) {
						$map[ (string) $o['value'] ] = (string) ( isset( $o['label'] ) ? $o['label'] : $o['value'] );
					} elseif ( is_scalar( $o ) ) {
						$map[ (string) $k ] = (string) $o;
					}
				}
			}
		}
	} catch ( \Throwable $e ) {
		// Never break the listing.
	}
	// Manual options.
	if ( empty( $map ) && ! empty( $field['options'] ) && is_array( $field['options'] ) ) {
		foreach ( $field['options'] as $k => $o ) {
			if ( is_array( $o ) && isset( $o['key'] ) ) {
				$map[ (string) $o['key'] ] = (string) ( isset( $o['value'] ) && '' !== $o['value'] ? $o['value'] : $o['key'] );
			} elseif ( is_array( $o ) && isset( $o['value'] ) ) {
				$map[ (string) $o['value'] ] = (string) ( isset( $o['label'] ) ? $o['label'] : $o['value'] );
			} elseif ( is_scalar( $o ) ) {
				$map[ (string) $k ] = (string) $o;
			}
		}
	}
	return $map;
}
/* =====================================================================
 * 5) NAMING CONVENTION
 * ===================================================================== */
function gt_target_by_name( $name ) {
	$name = strtolower( (string) $name );
	if ( '_id' === $name ) {
		return '';
	}
	$rules = array(
		'post_id' => 'post',
		'page_id' => 'post',
		'user_id' => 'user',
		'term_id' => 'term',
	);
	foreach ( $rules as $suffix => $target ) {
		if ( $name === $suffix || substr( $name, -strlen( '_' . $suffix ) ) === '_' . $suffix ) {
			return $target;
		}
	}
	// {cct_slug}_id → item of that CCT (property_id → CCT "property" / "properties").
	if ( strlen( $name ) > 3 && '_id' === substr( $name, -3 ) ) {
		$slug = gt_find_cct_slug( substr( $name, 0, -3 ) );
		if ( $slug ) {
			return 'cct:' . $slug;
		}
	}
	return '';
}
function gt_find_cct_slug( $base ) {
	static $cache = array();
	if ( isset( $cache[ $base ] ) ) {
		return $cache[ $base ];
	}
	$manager = gt_cct_manager();
	if ( ! $manager ) {
		return $cache[ $base ] = '';
	}
	$slugs = array();
	foreach ( array( $base, $base . 's', preg_replace( '/y$/', 'ies', $base ) ) as $v ) {
		$slugs[] = $v;
		$slugs[] = str_replace( '_', '-', $v );
		$slugs[] = str_replace( '-', '_', $v );
	}
	foreach ( array_unique( $slugs ) as $slug ) {
		if ( $slug && $manager->get_content_types( $slug ) ) {
			return $cache[ $base ] = $slug;
		}
	}
	return $cache[ $base ] = '';
}
/* =====================================================================
 * 6) RENDERING
 * ===================================================================== */
function gt_raw_to_html( $value ) {
	if ( is_array( $value ) ) {
		$value = implode( ', ', array_filter( $value, 'is_scalar' ) );
	}
	return esc_html( (string) $value );
}
/**
 * Returns escaped HTML, or null when nothing could be resolved (caller shows raw value).
 * Unresolvable IDs stay visible as #ID.
 */
function gt_ids_to_html( $value, $target ) {
	$ids = gt_parse_ids( $value );
	if ( empty( $ids ) ) {
		return null;
	}
	$out = array();
	foreach ( $ids as $id ) {
		$label = gt_id_to_label( $id, $target );
		$out[] = '' !== $label ? esc_html( $label ) : '#' . $id;
	}
	return implode( ', ', $out );
}
function gt_map_to_html( $value, $map ) {
	$values = gt_parse_values( $value );
	if ( empty( $values ) ) {
		return null;
	}
	$out   = array();
	$found = false;
	foreach ( $values as $v ) {
		if ( isset( $map[ $v ] ) ) {
			$out[] = esc_html( $map[ $v ] );
			$found = true;
		} else {
			$out[] = esc_html( is_numeric( $v ) ? '#' . $v : $v );
		}
	}
	return $found ? implode( ', ', $out ) : null;
}
/* =====================================================================
 * 7) JetEngine CCT — overrides existing admin columns
 * ===================================================================== */
/**
 * Raw field definitions of a CCT (incl. options_source / query_id).
 */
function gt_cct_fields( $factory ) {
	$fields = array();
	try {
		$raw = ( function () {
			return isset( $this->fields ) ? $this->fields : null;
		} )->call( $factory );
	} catch ( \Throwable $e ) {
		$raw = null;
	}
	if ( empty( $raw ) && method_exists( $factory, 'get_formatted_fields' ) ) {
		$raw = $factory->get_formatted_fields();
	}
	foreach ( (array) $raw as $key => $field ) {
		if ( ! is_array( $field ) ) {
			continue;
		}
		$name = isset( $field['name'] ) ? $field['name'] : $key;
		$fields[ $name ] = $field;
	}
	return $fields;
}
add_filter(
	'jet-engine/custom-content-types/admin-columns',
	function ( $columns, $factory ) {
		$slug   = $factory->get_arg( 'slug' );
		$config = gt_id_label_map();
		$manual = isset( $config['cct'][ $slug ] ) ? $config['cct'][ $slug ] : array();
		$fields = gt_cct_fields( $factory );
		foreach ( $columns as $name => $column ) {
			if ( '_ID' === $name || ! is_array( $column ) ) {
				continue;
			}
			$field = isset( $fields[ $name ] ) ? $fields[ $name ] : array();
			// 1) Manual config.
			$target = isset( $manual[ $name ] ) ? $manual[ $name ] : '';
			// 3) Naming convention / 4) Posts field type — used when options source gives nothing.
			$fallback = gt_target_by_name( $name );
			if ( ! $fallback && isset( $field['type'] ) && 'posts' === $field['type'] ) {
				$fallback = 'post';
			}
			$has_options = ! empty( $field['options_source'] ) || ! empty( $field['query_id'] )
				|| ! empty( $field['options_from_glossary'] ) || ! empty( $field['options'] );
			if ( ! $target && ! $has_options && ! $fallback ) {
				continue; // Plain field — leave column untouched.
			}
			$original_cb = isset( $column['_cb'] ) && is_callable( $column['_cb'] ) ? $column['_cb'] : null;
			$columns[ $name ]['_cb'] = function ( $value ) use ( $target, $field, $has_options, $fallback, $original_cb ) {
				static $options_cache = array();
				$args = func_get_args();
				// 1) Manual config.
				if ( $target ) {
					$html = gt_ids_to_html( $value, $target );
					if ( null !== $html ) {
						return $html;
					}
				}
				// 2) Field's options source (lazy, built once per field).
				if ( $has_options ) {
					$key = md5( wp_json_encode( $field ) );
					if ( ! isset( $options_cache[ $key ] ) ) {
						$options_cache[ $key ] = gt_field_options_map( $field );
					}
					if ( $options_cache[ $key ] ) {
						$html = gt_map_to_html( $value, $options_cache[ $key ] );
						if ( null !== $html ) {
							return $html;
						}
					}
				}
				// 3/4) Naming convention or Posts field type.
				if ( $fallback ) {
					$html = gt_ids_to_html( $value, $fallback );
					if ( null !== $html ) {
						return $html;
					}
				}
				// Nothing resolved — keep JetEngine's own rendering.
				return $original_cb ? call_user_func_array( $original_cb, $args ) : gt_raw_to_html( $value );
			};
		}
		return $columns;
	},
	20,
	2
);
/* =====================================================================
 * 8) CPT + taxonomy list tables — adds a readable column per meta key
 * ===================================================================== */
function gt_column_title( $key ) {
	return ucfirst( trim( str_replace( array( '_', '-' ), ' ', $key ) ) );
}
add_action(
	'admin_init',
	function () {
		$map = gt_id_label_map();
		foreach ( $map['post_type'] as $post_type => $fields ) {
			add_filter(
				"manage_{$post_type}_posts_columns",
				function ( $cols ) use ( $fields ) {
					foreach ( $fields as $key => $target ) {
						$cols[ 'gt_' . $key ] = gt_column_title( $key );
					}
					return $cols;
				}
			);
			add_action(
				"manage_{$post_type}_posts_custom_column",
				function ( $col, $post_id ) use ( $fields ) {
					if ( 0 !== strpos( $col, 'gt_' ) ) {
						return;
					}
					$key = substr( $col, 3 );
					if ( ! isset( $fields[ $key ] ) ) {
						return;
					}
					$html = gt_ids_to_html( get_post_meta( $post_id, $key, true ), $fields[ $key ] );
					echo null === $html ? '—' : $html; // already escaped
				},
				10,
				2
			);
		}
		foreach ( $map['taxonomy'] as $taxonomy => $fields ) {
			add_filter(
				"manage_edit-{$taxonomy}_columns",
				function ( $cols ) use ( $fields ) {
					foreach ( $fields as $key => $target ) {
						$cols[ 'gt_' . $key ] = gt_column_title( $key );
					}
					return $cols;
				}
			);
			add_filter(
				"manage_{$taxonomy}_custom_column",
				function ( $content, $col, $term_id ) use ( $fields ) {
					if ( 0 !== strpos( $col, 'gt_' ) ) {
						return $content;
					}
					$key = substr( $col, 3 );
					if ( ! isset( $fields[ $key ] ) ) {
						return $content;
					}
					$html = gt_ids_to_html( get_term_meta( $term_id, $key, true ), $fields[ $key ] );
					return $content . ( null === $html ? '—' : $html );
				},
				10,
				3
			);
		}
	}
);

Comments

Add a Comment