1

I am writing a little plugin that creates a custom post type.

I created a filter that copies the content of such a post into another one.

Thereby I loop through all the custom posts. For each one I get a target_type field value of it.

This value is compared to the actual post_type of the viewed post. If it is the same the content will be appended.

My problem is that shortcodes that are used in the custom post content shall be rendered in the context of the target post.

For Example: I have a shortcode used in the custom post, that just returns get_the_title(); In the target post this shows the title of the custom post.

In fact I want the custom post just to be a container for later rendered content.

Wow this was actually hard to explain for me.

I hope someone understands my issue and can help me out.

Thank you in advance!

Here is the filter code:

add_filter('the_content', 'copy_content');
function copy_content( $content )
{

    $post_type = get_post_type();

    $args = array(
        'post_type' => 'custom',
        'post_status' => 'publish',
        'posts_per_page' => -1
    );

    $post_query = new WP_Query($args);
    if($post_query->have_posts() ) {
      while($post_query->have_posts() ) {
        $post_query->the_post();
        $target_type = get_post_meta(get_the_ID(), "target_type")[0];
        if($target_type == $post_type){
            return $content . get_the_content();
        }
      }
    }

  wp_reset_postdata();

  return $content;
}
0

When you use return in your function, the rest of the function will not run. It work somehow like exit(); or die();, but it won't terminate the entire script, only ends that particular piece of code in your function, and return a value if necessary.

You should save your content into a string, and then return it all after you are finished.

So, that's how your code should look like:

add_filter('the_content', 'copy_content');
function copy_content( $content )
{

    $post_type = get_post_type();

    $args = array(
        'post_type' => 'custom',
        'post_status' => 'publish',
        'posts_per_page' => -1
    );

    $post_query = new WP_Query($args);
    if($post_query->have_posts() ) {
      // Create an empty string
      $data = '';
      while($post_query->have_posts() ) {
        $post_query->the_post();
        $target_type = get_post_meta(get_the_ID(), "target_type")[0];
        if($target_type == $post_type){
            // Append each post's content to it
            $data .= get_the_content();
        }
      }
    }

  wp_reset_postdata();
  // Return both content and our custom data altogether
  return $content . $data;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.