Brandon Powell
Brandon Powell

Reputation: 105

Wordpress Shortcode Issus v2

I am trying to create a 'Contact Form' shortcode to use in WP. All works fine apart from getting to load on the WordPress site.

enter image description here

When I copy the [contact_form] into Page or Post and Preview on a Page it prints just text. I did the code right.

<?php

class Settings {
      // Conact Form shortcode

    public function allb_contact_form( $atts, $content = null  ) {
          //[contact_form]
          //get the attribute_escape
          $atts = shortcode_atts(
            array(),
            $atts,
            'contact_form'
          );
          //return HTML
          ob_start();
          include '/lib/inc/thmeplates/contact-form.php';
          return ob_get_clean();

        add_shortcode( 'contact_form', 'allb_contact_form' );
    }

} new Settings();

Upvotes: 2

Views: 3809

Answers (1)

James Jones
James Jones

Reputation: 3899

Your add_shortcode() function call needs to refer to the containing class. So if add_shortcode() was called from outside the class you need to do.

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

That example is from https://codex.wordpress.org/Function_Reference/add_shortcode

If called from within class you refer to the class within itself like so:

add_shortcode( 'baztag', array( $this , 'baztag_func' ) );

Also, you can't add the shortcode from the same function that outputs the shortcode. So try the following:

<?php

class Settings {
      // Conact Form shortcode

    public function __construct(){
        add_shortcode( 'contact_form', array($this , 'allb_contact_form' ));
    }

    public function allb_contact_form( $atts, $content = null  ) {
          //[contact_form]
          //get the attribute_escape
          $atts = shortcode_atts(
            array(),
            $atts,
            'contact_form'
          );
          //return HTML
          ob_start();
          include '/lib/inc/thmeplates/contact-form.php';
          return ob_get_clean();             
    }

} new Settings();

Upvotes: 3

Related Questions