skip to Main Content

I have a function that can load any page content to another page simply like this:

add_shortcode( 'load_content', 'fc_load_content' );
function fc_load_content($params) {
    extract(shortcode_atts(array('id' => -1), $params));

    return apply_filters('the_content', get_post($id)->post_content);
}

In any page I can add block with [load_content id="123"] and it will load content of page id 123 to another page. Thats ok. But when I do [load_content id="123"] in page with ID 123 it will cause infinite loop till execution timeout. It’s user problem – wrong ID. But how to break this infinite loading loop in function fc_load_content? I wasn’t able to get ID of "calling" page so I can’t compare it to param ID. Thank you.

2

Answers


  1. Don’t worry about getting the id of the calling page.

    Just check that the current page is not the page with the id the shortcode is loading. The function is_page() can take an id parameter and returns true or false if that’s the current page. Negate it on a conditional gate wrapping your return statement…

    add_shortcode( 'load_content', 'fc_load_content' );
    function fc_load_content($params) {
        extract(shortcode_atts(array('id' => -1), $params));
        if ( !is_page($id) ) {
          return apply_filters('the_content', get_post($id)->post_content);
        }
    }
    
    Login or Signup to reply.
  2. add_shortcode( 'load_content', 'fc_load_content' );
    function fc_load_content($params) {
        extract(shortcode_atts(array('id' => -1), $params));
        remove_sortcode( 'load_content' );
        $content = apply_filters('the_content', get_post($id)->post_content);
        add_sortcode( 'load_content', 'fc_load_content' );
        return $content;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search