Shortcode for display posts in wp-editor

Declaring a shortcode is as easy as using this:

add_shortcode('jobs', 'callback_function');
function callback_function(){ 
    $content="";
    $args = array(
        'post_type' => array('job'),
        'posts_per_page' => 20
    );
    $the_query = new WP_Query( $args );
    if ($the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            if ( 683 !== get_the_ID() ) { 
                $content .= '<a href="'. get_the_permalink().'" class="jobs">';
            }
            $content .= '
                <div class="jobs-item">
                    <h2 class="page-head_sub-title">'.get_the_title().'</h2>
                    <p>'. get_the_content() .'</p>
                </div>';
            if ( 683 !== get_the_ID() ) {
                $content .= '</a>';
            } 
        }
    }
    wp_reset_postdata();
    return '
    <div class="owl-carousel-wrap jobs-carousel">
        <div id="jobsCarousel" class="owl-carousel ">
            '.$content.'
        </div>

        <div class="js-control-jobs">
            <div class="carousel-control-prev"><span class="icon-arrow"><!--icon--></span></div>
            <div class="carousel-control-next"><span class="icon-arrow"><!--icon--></span></div>
        </div>
    </div>';

}

Wrap your code in a function, and replace callback_function with your function’s name. Then you can use it in the editor as [shortcode-name].

However, you should notice that you can not use echo inside a shortcode function. You should store your content in a variable, and then return the variable.

This means you can’t use functions that echo the content, such as the_content() or the_title(). You should use get_the_content() or get_the_title() instead.

Note: The reason that I didn’t use apply_filters('the_content', get_the_contnet()); is that if you use this shortcode in a post and then the post is included in this loop, this loop will be an infinite one, since the filter will run the shortcode again, which runs a nested shortcode and so on.

tech