Skip to content

Instantly share code, notes, and snippets.

@ginsterbusch
Created May 27, 2021 12:25
Show Gist options
  • Save ginsterbusch/1c9ec55121aa134fd90de37327fbe504 to your computer and use it in GitHub Desktop.
Save ginsterbusch/1c9ec55121aa134fd90de37327fbe504 to your computer and use it in GitHub Desktop.
Inserts content of a custom meta field using a shortcode. Use [mfs_custom_field field='my_field_name'] to insert any kind of meta field value inside of your posts.
<?php
/**
* Plugin Name: Metafield Shortcode Micro Plugin.
* Description: Inserts content of a custom meta field using a shortcode. Use [mfs_custom_field field='my_field_name'] to insert any kind of meta field value inside of your posts. Works both in WP v3.7 - 5.x and ClassicPress.
* Version: 1.0
* Author: Fabian Wolf
* Author URI: https://usability-idealist.net/
* License: GNU GPL v2
*/
/**
* Usage instruction:
* 1. Save this file to your local system
* 2. Upload the file to your wp-content/plugins/ folder
* 3. Head over to the WordPress admin, and active the plugin under Plugins :)
*/
if( !function_exists( '_mfs_add_custom_field_shortcode' ) ) {
function _mfs_add_custom_field_shortcode( $attr, $content = '' ) {
$return = $content;
// default attributes, which are being used if no value is set, but also, to only allow these specific variables
$default_attr = array(
'field' => '_my_custom_field_name',
'title' => 'Videodauer:',
'html_class' => 'custom_field_value_wrapper',
);
$params = shortcode_atts( $default_attr, $attr );
/**
* Extract parsed parameters into the current scope. Avoid overriding existing variables.
* Also see @link https://www.php.net/extract
*/
extract( $params, EXTR_SKIP );
$field_value = get_post_meta( get_the_ID(), $field, true );
/**
* NOTE: only generate return data if our field both exists AND contains any kind of data ;)
* Construct the return value in HTML.
*/
if( !empty( $field_value ) ) {
$return = '<div';
if( !empty( $html_class ) ) {
$return .= ' class="' . $html_class . '"';
}
$return .= '">';
if( !empty( $title ) ) {
$return .= '<strong>' . $title . '</strong>';
}
// additional tag for better styling :)
$return .= '<span>' . $field_value . '</span>';
$return .= '</div>';
}
return $return;
}
/**
* Usage:
*
* [mfs_custom_field field="meta field name" title="optional title" html_class="my-html-class and-some moar"]
*
*
* @param string $field The name of the meta field to extract the content from. Required.
* @param string $title Optional custom title.
* @param string $html_class Optional HTML wrapper class.
*/
add_shortcode( 'mfs_custom_field', '_mfs_add_custom_field_shortcode' );
}
// closing tag intentionally left out ^^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment