Automatically insert php function into post $the_content

I am trying to have 2 php functions automatically inserted in every post for my CPT. The problem I am having is that even though I’ve found a way to add text, Im not sure how to add the php functions cause with the code I have it adds it as regular text to the post.

This is what I have in my functions file —

    add_filter( 'default_content', 'my_editor_content', 10, 2 );

    function my_editor_content( $content, $post ) {

        switch( $post->post_type ) {
            case 'property':
 $content = "<div>";
                $content . "<?php if ( class_exists( 'MRP_Multi_Rating_API' ) ) {
        MRP_Multi_Rating_API::display_rating_result( array(
                'rating_item_ids' => 2,
                'show_count' => false,
                'result_type' => 'value_rt',
    'no_rating_results_text' => 'Not Rated'
        ) ); } ?><?php if ( class_exists( 'MRP_Multi_Rating_API' ) ) {
        MRP_Multi_Rating_API::display_rating_result( array(
                'rating_item_ids' => 5,
                'show_count' => false,
                'result_type' => 'overall_rt',
    'no_rating_results_text' => 'Not Rated'
        ) );
    } ?>";
 $content = "</div>";
            break;
            default:
                $content = "your default content";
            break;
        }

        return $content;
    }

How can I fix this so my functions work and is it possible to make it add to every post not just the new ones created?

Thanks

2 Answers
2

I’m sure you want to use the_content filter instead of the default_content filter (already mentioned by @jgraup) because what happens if the generated HTML changes? Then you’re stuck with it in your content. It’s better to add it dynamically. Here’s one suggestion:

add_filter( 'the_content', function( $content)
{
    if( ! in_the_loop() )
        return $content;

    if( 'property' !== get_post_type() )
        return $content;

    $args = [
        'rating_item_ids'           =>  2,
        'show_count'                => false,
        'result_type'               => 'value_rt',
        'no_rating_results_text'    => 'Not Rated',
        'echo'                      => 0,
    ];

    if ( class_exists( 'MRP_Multi_Rating_API' ) ) 
    {
        $content .= MRP_Multi_Rating_API::display_rating_result( $args ); 

        // Modify arguments for the second run
        $args['rating_item_ids'] = 5;
        $args['result_type']     = 'overall_rt';

        $content .= MRP_Multi_Rating_API::display_rating_result( $args ); 
    }

    return $content;
} );

Notice that we use the in_the_loop check (here I link to the question by @PieterGoosen and the answer by @gmazzap), because I assume you don’t want this added to every content part of your site.

You also don’t need to check twice for the existince of the same class.

Note that this has one big assumption, namely the echo attribute 😉

Leave a Comment