Last active
November 21, 2023 15:25
-
-
Save zackpyle/8e0d7b8a6b85088c7bc60a3a3127f926 to your computer and use it in GitHub Desktop.
Shortcode to output an ACF field with user defined truncation length #acf
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 //ignore this line - only for formatting | |
add_shortcode("truncated_acf_field", "truncated_acf_field_shortcode"); | |
function truncated_acf_field_shortcode($atts) | |
{ | |
if (function_exists("get_field")) { | |
$atts = shortcode_atts( | |
[ | |
"length" => 100, // Set the default to 100 characters if user doesn't define their own in the shortcode | |
"name" => "", | |
"ellipsis" => "true", // Defaults to true if user leaves this out of the shortcode | |
], | |
$atts | |
); | |
if (empty($atts["name"])) { | |
return "Please add an ACF field name to the shortcode"; | |
} | |
$field_value = get_field($atts["name"]); | |
// Truncate the description to the defined number of characters and trim white space at the end | |
$truncated_field_value = mb_substr($field_value, 0, $atts["length"]); | |
$truncated_field_value = rtrim($truncated_field_value); | |
// Add the ellipsis if the attribute is true and the original value is longer than the defined length | |
if ( | |
$atts["ellipsis"] === "true" && | |
mb_strlen($field_value) > $atts["length"] | |
) { | |
$truncated_field_value .= "..."; | |
} | |
return $truncated_field_value; | |
} else { | |
return "<p>Please activate the Advanced Custom Fields plugin</p>"; | |
} | |
} | |
// And your shortcode will look like [truncated_acf_field name="field_name" length="150"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment