Skip to content

Instantly share code, notes, and snippets.

@WPAcademic
Last active October 23, 2021 15:19
Show Gist options
  • Save WPAcademic/830168f47ddec2e38d07c32a8fe4dce5 to your computer and use it in GitHub Desktop.
Save WPAcademic/830168f47ddec2e38d07c32a8fe4dce5 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: Get ACF Field Label from Name
* Plugin URI: https://wpacademic.com
* Version: 1.0.0
* Author: Louis Fico
* Author URI: https://profiles.wordpress.org/louis
* Description: Adds function to get ACF field name from its label
* License: GPL2
*/
/**
* Ultimately, you may want to put this in your own class,
* in which case you can put your own namespace here
*/
// namespace AcfMissingFunctions;
// use Exception;
if( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
// avoid function naming collisions
if (!function_exists('getAcfLabelByName')) {
function getAcfLabelByName($fieldName) {
if (empty($fieldName)) {
return 'No field name specified';
}
// set a default in case there's an exception
$fieldLabel = 'Not Found';
try {
/**
* ACF stores the the Labels in the
* wp_posts table, where the ACF label is the title
* and the excerpt is the field name
*/
global $wpdb;
$tableName = "{$wpdb->prefix}posts";
$labelReturned = $wpdb->get_var( $wpdb->prepare( "SELECT `post_title` FROM `$tableName`
WHERE `post_type` = %s AND `post_excerpt` = %s", 'acf-field', $fieldName ));
// grab the post_title from the result
$fieldLabel = !empty($labelReturned) ? $labelReturned : 'Not Found';
} catch (Exception $e) {
$error = $e->getMessage();
error_log("There was an exception finding the ACF field label by name with the message $error");
}
return $fieldLabel;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment