Insert PHP Code to your WordPress Post or Page

Date Posted: July 31, 2014, 7:50 am


php-code-pic

Add this code snippet into your functions.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function cvf_insert_php($content) {

    $cvf_content = $content;
    preg_match_all('!\[php[^\]]*\](.*?)\[/php[^\]]*\]!is',$cvf_content,$cvf_matches);
    $cvf_nummatches = count($cvf_matches[0]);
    for( $cvf_i=0; $cvf_i<$cvf_nummatches; $cvf_i++ ) {
        ob_start();
        eval($cvf_matches[1][$cvf_i]);
        $cvf_replacement = ob_get_contents();
        ob_clean();
        ob_end_flush();
        $cvf_search = quotemeta($cvf_matches[0][$cvf_i]);
        $cvf_search = str_replace('/',"\\".'/',$cvf_search);
        $cvf_content = preg_replace("/$cvf_search/",$cvf_replacement,$cvf_content,1);
    }
    return $cvf_content;
}

add_filter( 'the_content', 'cvf_insert_php', 9 );

Then on your WP editor, you can start your PHP code by using the shortcode: “[php]” instead of “<?php”. The ending tag of your PHP would be “[/php]” and NOT “?>”

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me