wordpress reusable content blocks

I am using a custom post type to allow the editor of the site to add a number of blocks of content to the site – infoboxes.

Now i would like to give the editor the possibility to choose which boxes appear on which pages.

Read More

So if i have defined page 1 and page 2 is there a way to allow the user to choose that on page 1 the infoboxes a and b are shows and on page 2 the infoboxes m and n?

Thanks.

Related posts

Leave a Reply

1 comment

  1. One of two ways:

    Add a shortcode, so someone could drop in [content-block id="12"] wherever they wanted. Here’s a very simple example without a lot of error checking.

    <?php
    add_action( 'init', 'wpse29418_add_shortcode' );
    function wpse29418_add_shortcode()
    {
        add_shortcode( 'content-block', 'wpse29418_shortcode_cb' );
    }
    
    function wpse29418_shortcode_cb( $atts )
    {
        $atts = shortcode_atts(
                    array(
                        'id' => 0
                    ),
                    $atts
                );
        // then use get_post to fetch the post content and spit out.
        $p = get_post( $atts['id'] );
        return $p->post_content;
    }
    

    Alternatively, you could create a very large options page on the back end that allows users to assign content blocks to pages. Then hook into the_content and place the info boxes.

    <?php
    add_filter( 'the_content', 'wpse29418_content_filter' );
    function wpse29418_content_filter( $content )
    {
        global $post;
    
        // get the option that stores the data.
        $opts = get_option( 'wspe29418_opts' );
    
        // check to see if the post has a content block assigned.
        if( isset( $opts[$post->ID] ) )
        {
            //do stuff here
        }
        return $content;
    }
    

    The downside to the second approach is there you’re limited to either placing the content block before or after the original post content or replacing that post’s content all together.

    Shortcodes would be the most flexible for your end user.