Skip to content

Instantly share code, notes, and snippets.

@newsapkota
Forked from danielpataki/abstraction-1.php
Created February 7, 2018 13:00
Show Gist options
  • Save newsapkota/18c5a9aad420c1db48bcdf086b9259c3 to your computer and use it in GitHub Desktop.
Save newsapkota/18c5a9aad420c1db48bcdf086b9259c3 to your computer and use it in GitHub Desktop.
OOP in Plugins
<div class='post' id='post-23'>
<h2><?php the_title() ?></h2>
<div class='excerpt'>
<?php
$content = get_the_content();
if( strlen($content) < 250 ) {
echo $content;
}
else {
$content = substr( $content, 0, 250 );
echo $content . '...';
}
?>
</div>
</div>
<div class='post' id='post-23'>
<h2><?php the_title() ?></h2>
<div class='excerpt'>
<?php the_excerpt() ?>
</div>
</div>
<?php
/*
Plugin Name: Written By Awesome
Description: Adds a nice author tagline
Version: 1.0.0
Author: Daniel Pataki
Author URI: http://danielpataki.com
*/
class Written_By_Awesome {
function __construct() {
add_filter( 'the_content', array( $this, 'add_author_line_to_content' ) );
}
function add_author_line_to_content( $content ) {
return $content . '<br> Written by someone awesome';
}
}
$written_by_awesome = new Written_By_Awesome();
<?php
class PostsByCommentBackend {
function construct() {
add_action( 'pre_get_posts', array( $this, 'backend_query' ) );
}
function backend_query( $query ) {
if ( ! $query->is_admin() ) {
$query->set( 'orderby', 'comment_count' );
$query->set( 'order', 'DESC' );
}
}
}
class PostsByCommentFrontend {
function construct() {
add_action( 'pre_get_posts', array( $this, 'frontend_query' ) );
}
function frontend_query( $query ) {
if ( $query->is_admin() ) {
$query->set( 'orderby', 'comment_count' );
$query->set( 'order', 'DESC' );
}
}
}
$backend = new PostsByCommentBackend();
$frontend = new PostsByCommentFrontend();
class Post {
function get_excerpt( $content ) {
if( strlen($content) < 250 ) {
return $content;
}
else {
$excerpt = substr( $content, 0, 250 );
return $excerpt . '...';
}
}
function the_excerpt( $content ) {
echo get_excerpt( $content );
}
function the_title( $title ) {
echo $title;
}
}
class Post {
var $title;
var $content;
function __construct( $data ) {
$this->title = $data['title'];
$this->title = $data['content'];
}
function get_excerpt() {
if( strlen($this->content) < 250 ) {
return $this->content;
}
else {
$excerpt = substr( $content, 0, 250 );
return $excerpt . '...';
}
}
function the_excerpt() {
echo $this->get_excerpt();
}
function the_title() {
echo $this->title;
}
}
$postdata = array(
'title' => 'Post 1 Title',
'content' => 'Content of Post 1'
);
$post = new Post( $postdata );
$post->the_excerpt();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment