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?

closed as off-topic by Krzysiek Dróżdż, TheDeadMedic, bosco, Jacob Peattie, Jack Johansson Aug 11 at 14:53

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • Use $themeSettings->getData(); and not just getData();.. – Sally CJ Aug 9 at 21:30
  • same error. sory. – bilimokur Aug 9 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 Aug 9 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 Aug 9 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()... – Krzysiek Dróżdż Aug 10 at 7:32
up vote 2 down vote accepted

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.
 */
  • You are welcome. Glad to help :) – Serkan Algur Aug 10 at 9:06

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