• Hello,
    I am trying to turn get_posts() into a shortcode function so that I don’t have to keep hard-coding new page templates every time I want to reference my blog on a given site page. As this is my first attempt at shortcode creation, I’m trying to keep it simple at first.

    Here’s what I have so far:

    function add_blog() {
    
    	$args = array(
            'posts_per_page'   => 10,
    	'offset'           => 0,
    	'category'         => '',
    	'orderby'          => 'post_date',
    	'order'            => 'DESC',
    	'include'          => '',
    	'exclude'          => '',
    	'meta_key'         => '',
    	'meta_value'       => '',
    	'post_type'        => 'post',
    	'post_mime_type'   => '',
    	'post_parent'      => '',
    	'post_status'      => 'publish',
    	'suppress_filters' => true ); 
    
    	$myposts = get_posts( $args );
    	$postlink = the_permalink();
    	$posttitle = the_title();
    	$posttime = the_time('M d Y');
    	$postcomments = comments_popup_link('No Comments', '1 Comment', '% Comments');
    
    	$postsetup = '<ul class="blogPosts">
    		foreach ( $myposts as $post ) : setup_postdata( $post );
    		<li>
    		<h3><a href="$postlink" title="$posttitle">
    $posttitle</a></h3>
    		<span class="postBody">$posttime | $postcomments</span>
    		</li>
    		endforeach;
    		wp_reset_postdata();
    	</ul>

    As you can see, I’m setting up the parameters for get_posts in the $args array, then setting up all the other functions I need in other strings to be called during the execution.

    $postsetup is the string which will be put it all together and create the unordered list that I can style on the front end, the string which will be targeted by the “return” command. I’m just not sure how to setup this final string so that it will work properly. Tutorial sites I’ve reviewed use lots of odd punctuation in their examples which they don’t take the time to explain.

    I’m new at this as I said, so any help anyone can provide would be greatly appreciated.

The topic ‘Trying to turn get_posts() into shortcode function, need assistance’ is closed to new replies.