Monday, February 18, 2019

WordPress | Automatically Insert Content After Each WordPress Post or Page

For example, on all the our posts and pages, we have an email subscription box. There are several ways to add content to your post, without having to do so manually
Most efficient way is using a filter to add content to your post content
<?php
define("MY_FIRST_PLUGIN_DIR", plugin_dir_path(__FILE__));
add_filter('the_content', 'my_the_content');
function my_the_content($c) {
    if (!is_admin() && !is_feed() && (is_single() || is_page())) {
        global $post;
        $allow = !is_null($post) && property_exists($post, "post_type") && in_array($post->post_type, array('post', 'page'));
        if ($allow) {
            ob_start();
            include MY_FIRST_PLUGIN_DIR . "templates/page_content.php";
            $content = ob_get_contents();
            ob_end_clean();
            $c = $c . $content;
        }
    }
    return $c;
}

1 comment: