Last active
April 11, 2019 04:07
-
-
Save trvswgnr/5800689a9a62f3f97a2b103e3e6b51f0 to your computer and use it in GitHub Desktop.
Create a reusable WordPress module with OOP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class: Example Module | |
* | |
* @package projectname | |
* @subpackage modules | |
*/ | |
/** | |
* Example Module | |
*/ | |
class Example_Module { | |
/** | |
* Construct | |
* | |
* @param bool|string $style_uri (Optional) Specify stylesheet URI. | |
*/ | |
public function __construct( $style_uri = false ) { | |
$this->styles( $style_uri ); | |
} | |
/** | |
* Hero | |
* | |
* @param array $args Arguments. | |
*/ | |
public function hero( $args = array() ) { | |
$defaults = array( | |
'heading' => 'Et eaque et suscipit et voluptate.', | |
'content' => 'Placeat sunt deleniti. Sed eum aut neque laboriosam repellendus quaerat.', | |
); | |
$args = wp_parse_args( $args, $defaults ); | |
ob_start(); | |
?> | |
<div class="hero"> | |
<h1 class="hero__heading"><?php echo esc_html( $args['heading'] ); ?></h1> | |
<div class="hero__content"> | |
<?php echo wp_kses_post( $args['content'] ); ?> | |
</div> | |
</div> | |
<?php | |
echo wp_kses_post( ob_get_clean() ); | |
} | |
/** | |
* Styles | |
* | |
* @param bool|string $style_uri External stylesheet. | |
*/ | |
private function styles( $style_uri = false ) { | |
ob_start(); | |
?> | |
<style> | |
.hero { | |
background: #ddd; | |
padding: 2em 6em; | |
} | |
.hero__heading { | |
font-size: 2em; | |
} | |
.hero__content { | |
max-width: 600px; | |
} | |
</style> | |
<?php | |
wp_register_style( 'case-study', $style_uri, array(), '1.0.0' ); | |
wp_enqueue_style( 'case-study' ); | |
wp_add_inline_style( 'case-study', ob_get_clean() ); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Template Name: Example | |
* | |
* @package projectname | |
* @subpackage templates | |
*/ | |
get_header(); | |
require_once module( 'class-example-module' ); | |
$example_module = new Example_Module(); | |
$args = array( | |
'heading' => 'Some Custom Heading', | |
'content' => 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Suscipit corporis aliquam rerum eos ducimus error, repellendus ea velit unde ipsum cum delectus, quo magnam ut asperiores iure eius cupiditate nesciunt?', | |
); | |
$example_module->hero( $args ); | |
get_footer(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment