• I’m using object design approach in snippets and am using private variables with public functions. I use the old insert php method to make a “new” object of a class I created, however, I can’t call any functions from the class I created. Any idea how to call functions from classes within the new shortcode?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author webcraftic

    (@webcraftic)

    Hi,
    1. If you want to place a class in a snippet and use it in any shortcode.
    Create a snippet with the class, the class must be global. Set in the snippet settings “run everywhere”.
    http://joxi.ru/brRzEXgTJL95Yr

    global $wbcr_my_public_class;
    	
    class Wbcr_PublicClass {	
      private $product_name = 'book';
      
      public function show_my_method_text() {
        return 'Return My value';
      } 
      public function show_product_name() {
        return $this->product_name;
      }
    }
    
    $wbcr_my_public_class = new Wbcr_PublicClass();

    2. Create a snippet with a shortcode and call your class, so
    http://joxi.ru/ZrJzOLBT9b4qZr

    global $wbcr_my_public_class;
    	
    if(!empty($wbcr_my_public_class) && $wbcr_my_public_class instanceof Wbcr_PublicClass) {
     	echo $wbcr_my_public_class->show_my_method_text(); 
      	echo $wbcr_my_public_class->show_product_name();    
    }

    Best regards, Alex

    Thread Starter codeyschoettle

    (@codeyschoettle)

    My goal is to call the function from the webpage itself. I want to make a function let’s say called “displayName();” within a snippet. I want to be able to call the function by passing POST data into the shortcode found on the page, like “[wbcr_php_snippet id=”249” displayName(“name”)]”

    Plugin Author webcraftic

    (@webcraftic)

    Hi,
    You do not need to pass data through the shortcode, you can get all the post data via the global variable $_POST inside the snippet.

    This code prints all the data sent by the post method on the page

    $post = $_POST;
    print_r($post);

    1. Create a snippet with a function, this snippet should be run everywhere

    function displayName($name) {
      echo $name;
    }

    2. Create a second snippet shortcode

    
    //$attr_name - the value of the variable is passed from the shortcode
    displayName($attr_name);
    

    Call the snippet using the shortcode, passing the value inside the function. You can pass data through a shortcode, so
    [wbcr_php_snippet id="249" attr_name="name"]

    Best regards, Alex

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Object Programming in snippets’ is closed to new replies.