0

I am trying to make something like this.

<?php 
class themeSettings {

    private $key = 'themeSettings';

    public function __construct( $key ) {
        global $post;
        $post_id = $post->ID;

        $settings = get_post_meta( $post_id, $this->key, true );
    }

    public function getData(){
        print_r( $settings['post_description'] );
    }
}

$themeSettings = new themeSettings();
?>

<?php
// Print 'post_description' values
getData();
?>

But it doesn't work. Where i am wrong?

5
  • Use $themeSettings->getData(); and not just getData();..
    – Sally CJ
    Commented Aug 9, 2018 at 21:30
  • same error. sory.
    – wpdev
    Commented Aug 9, 2018 at 22:05
  • 2
    $settings is local variable, exists only in constructor, it's undefined inside getData(). $settings should be a class property, not a variable.
    – nmr
    Commented Aug 9, 2018 at 22:38
  • 1
    @nmr is correct. So you could add private $settings; to your class, then in the __construct() and getData(), use $this->settings instead of $settings.
    – Sally CJ
    Commented Aug 9, 2018 at 23:53
  • But there is one more problem with your class - you use global $post variable in its constructor - but this variable may not be initialized (depending on when the constructor will be executed). Another problem is that you run getData() and not $themeSettings->getData()... Commented Aug 10, 2018 at 7:32

1 Answer 1

2

Can you try this. This should work. You don't need to use construct if you call getDatain your theme files. You key need to be static value. After that you can call it like self::$key

Use like this : echo $theme->getData(get_the_ID()); inform me if code works :)

<?php
class themeSettings {

    private static $key= 'themeSettings'; // We Need to create a static value
    public $id; // we nedd this for postID

    public function __construct() {}

    public function getData($id){
        //$des = get_the_title($id); For Testing
        $des =  get_post_meta($id,self::$key,true);
        /** All these area and If clause for testing */
        if($des){
            //return print_r($des); For testing
            return print_r($des['post_description']);
        } else {
            return 'Yok';
        }
    }
}

$theme = new themeSettings();

/**
 * Simple usage $theme->getData(get_the_ID());
 * Dont add global WordPress values to classes.
 */
1
  • You are welcome. Glad to help :) Commented Aug 10, 2018 at 9:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.