Render .twig file when shortcode called in WordPress?

I’ve been firefighting this for a while and I’m struggling with getting this shortcode to render this Twig partial when it is called. Anyone have any advice?

Thanks!

Read More

Here’s what I have so far:

<?php  namespace locwplib;
use Timber as Timber;
use Twig_SimpleFunction as Twig_SimpleFunction;
class LOCShortcodes {
  public function addSlider() {
    add_shortcode('feature-slider', 'feature_slider');
    function feature_slider() {
      return Timber::render('template-feature-slider.twig');
    }
  }
}

Related posts

Leave a Reply

1 comment

  1. When you work with hooks and filters (or shortcodes in your case) in a class context, you need to define the callback a little differently.

    The last example in https://codex.wordpress.org/Function_Reference/add_shortcode shows you how you use shortcodes with classes:

    <?php
    
    class MyPlugin {
        public static function baztag_func( $atts, $content = "" ) {
            return "content = $content";
        }
    }
    
    add_shortcode( 'baztag', array( 'MyPlugin', 'baztag_func' ) );
    

    As you can see, the shortcode is added outside of the class. If you want to add it inside your class, then you don’t have to explicitly use the name of the class, but you can use $this:

    <?php
    
    class MyPlugin {
        public function __construct() {
            add_shortcode( 'baztag', array( $this, 'baztag_func' ) );
        }
    
        public static function baztag_func( $atts, $content = "" ) {
            return "content = $content";
        }
    }
    

    In your case, you could do it like this:

    <?php
    
    class LOCShortcodes {
        public function __construct() {
            add_shortcode( 'feature-slider', array( $this, 'feature_slider' ) );
        }
    
        public function feature_slider() {
            return Timber::compile( 'template-feature-slider.twig' );
        }
    }
    

    Don’t forget to use Timber::compile() instead of Timber::render(), because the render() function is echoing the output, while for shortcodes, the output should be returned. This is also mentioned in the Notes section in the Codex:

    Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results. […]

    Also make sure to read the wiki section about Shortcodes in Timber.