ACF Custom Shortcode Registration

<h3 class="entry-title">ACF Custom Shortcode Registration</h3>
Posted on



Advanced Custom Fields is an awesome plugin for WordPress. Below I will show how one can use it to create custom shortcodes to be used in the post's WYSIWG editor.

  1.  Enqueue prism.js and prism.css
    /**
     * Enqueue scripts and styles.
     */
    function my_scripts() {
    	wp_enqueue_style( 'prism-css', get_template_directory_uri() . '/css/prism.css');
    	wp_enqueue_script( 'prism-js', get_template_directory_uri() . '/js/prism.js', array(), '20180501', true );
    
    	
    }
    add_action( 'wp_enqueue_scripts', 'my_scripts' );
  2.  Hook into acf/format_value/{name}=custom_field_name

    /**
     *  Hook into filter for custom 'Translations' ACF Repeater Field and register to create a custom shortcode 
     *  that can be used in the WYSIWYG editor of the same page
     *  
     *  https://www.advancedcustomfields.com/resources/acf-format_value/
     * 
     */
    function prepare_code_snippet_shortcodes( $field ) {
    	// Register Shortcodes
    	$snippet_idx = 1;
    	foreach( $field as $f) {
    		$name = 'code_' . $snippet_idx;
    		$snippet_idx = $snippet_idx + 1; 
    		add_shortcode( $name, function() use ( $name, $f ) {
    			$keys = array_keys($f);
    			$class = $f[$keys{0}] ;
    			$content = $f[$keys{1}] ;  
    			return '<pre><code class="language-'. $class .'">' . $content . '</code></pre>';
    		});
    	}
        return $field;
    }
    add_filter('acf/format_value/name=codes', 'prepare_code_snippet_shortcodes');

    It's important to note that format_value does not by default trigger on a page load, it is triggered by a function such as get_field() or get_field_objects()

     

  3. Result