Short Code to get Custom Field on Post

Short Code to get Custom Field on Post had been quite a difficult task as the CFS has many options for field types. Install Plugin “ShortCode Exce PHP” and Add a New Short Code with Name: “get_Fields” and in the code area enter the code below.

The Usage is [get_Fields arg=”Custom_Field_Slug”] will return the Value in the Custom_Field_Slug. If Error then the Error is also displayed

/* short code for getting the custom field set using
 * Custom Field Suite
 * using "ShortCode Exce PHP" Plugin
 */

extract(shortcode_atts(array('arg' => 'default'), $atts));
global $cfs;

if ($arg !== 'default') {
    // get all the custom field in the post //
    $AllFields = CFS()->get(false);
    // Get the Keys from the Array //
    $AllKeys = array_keys($AllFields);
    $flipped_haystack = array_flip($AllKeys); 
    
    // Find if the asked Custom Field is available in Post //
    if ( isset($flipped_haystack[$arg]) ) 
    { 
        // echo 'Yes it\'s there!<br />';
        $getFields = CFS()->get($arg);
        // var_dump($getFields . '<br/>');
        
        // Check if return is array or not //
        if (is_array($getFields)) { 
            // echo 'is Array <br />';
            // code to list each element of the Array //
            $it = new CachingIterator(new ArrayIterator($getFields));
            foreach($it as $key => $value) {
                if (!$it->hasNext()) {
                    echo $value;
                } else {
                    echo $value, '<br /> ';
                }
             }
        } else {
            // echo 'Not a Array <br />';
            echo $getFields . PHP_EOL;
        }
    } else {
        // Trap the error and display the list of Custom Filed on the Post //
        echo '<strong>' . $arg . ':</strong><span style="color:red"> Custom Field Not Found </span><br />' . '<strong>The Post Contains Following Custom Field </strong><br />';
        echo '<ul>';
        $it = new CachingIterator(new ArrayIterator($AllKeys));
        foreach($it as $key => $value) {
            if (!$it->hasNext()) {
                echo '<li>' .$value . '</li>';
            } else {
                echo '<li>' .$value, '</li>';
            }
        } 
        echo '</ul>';
        // List the Custom Field //
        // var_dump($AllKeys);
    }
} else {
    echo 'No \"Field\" Value Passed to Get data';
} // if ($arg !== 'default')
Posted in Wordpress and tagged , , .

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.