• This is my first foray into PHP development, so apologies if I’m missing the big picture. I know this has been done, but for learning purposes, I wanted to write my own latest posts template part (or plugin)? This may be where I’m getting confused.

    I have a homepage where I originally had this code embedded:

    class Latest_Posts {
    <?php
                $args = array(
                    'posts_per_page' => 3,
                    'category' => 3,
                );
    
                public $latestPosts = get_posts( $args );
                public $i = 0;
                /* FOR TESTING
                echo count($latestPosts);
                */
                ?>
                    <?php
                foreach ($latestPosts as $post) : setup_postdata($post); ?>
                    <div class="post"><h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3></div>
                    <?php
                        echo "TEST" . $i;
                        $i++;
                    ?>
    
                <?php endforeach; ?>
    }

    I have since separated the code into a new file, latest-posts.php where I was thinking of using an object oriented approach and instantiating an instance of the class in my original page by doing the following:

    <?php include('/wp-content/themes/twentyeleven_child/latest-posts.php'); ?>
                    <?php $the_latest_posts = new Latest_Posts(); ?>

    After I moved the code, nothing is showing up. I’m not sure if I should be following the plugin tutorials or the page template tutorials or am better off with the original solution of leaving the PHP code embedded in the page. My reasoning for moving the code would be for portability in case I wanted to call the it from another page template (a post, category or another custom page). Thanks in advance!!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter edwardlw

    (@edwardlw)

    you can ignore the following. It was used for debugging.

    <?php
                        echo "TEST" . $i;
                        $i++;
                    ?>

    You didn’t write a PHP class, but if you had, this is how you’d access it.

    <?php
    
    // This is a PHP class.
    class myClass
    {
        public $variable1 = 1;
    
        public function sayHi(){
            return 'hi';
        }
    
    }
    
    // This is how you create an instance your class.
    $object = new myClass;
    
    // This is how you call a function inside of your class.
    echo $object->sayHi();
    
    ?>
    Thread Starter edwardlw

    (@edwardlw)

    Thanks for the info. I forgot to paste in the class name. oops! I updated the original post. Maybe the problem is that I don’t have a return statement for the <div>s that I’m trying to output?

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘I wrote a PHP class. How Do I access it?’ is closed to new replies.