1

I'm building a shortcode to display certain posts in a page. So far it looks like this:

function bloghome( $atts ) {
    extract( shortcode_atts( array(
        'id' => 17      // Add the *default category id
    ), $atts ) );

    $posts = get_posts( array(
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'cat'       => $id,
    ) );
    $return = '';
    $return .= '<div class="row page-template-press bloghome">';
    foreach ( $posts as $post ) {
        $link = get_permalink( $post->ID);
        $title =  get_the_title($post->ID);
        $img =  get_the_post_thumbnail( $post->ID, 'medium' );
        $snippet = get_post_meta($post->ID, 'Snippet', true);
        $return .= '<article class="col-lg-'.$width.' col-md-'.$width.' col-sm-'.$width.'"><a href="'.$link.'"><header><div class="page-title-post">'.$title.'</div></header><div class="entry-content">'.$img.'<p class="snippet">'.$snippet.'</p></div></a></article>';
    } 

$return .= '</div>';
return $return;
}
add_shortcode( 'bloghome', 'bloghome' );  

I want to add a conditional though, to define column width if the post is sticky.

I've tried the following but it throws an error:

foreach ( $posts as $post ) {
    if ( is_sticky() ) {
        $width = '12'
    } else {
        $width = '4'
    };
    $link = get_permalink( $post->ID);
    $title =  get_the_title($post->ID);
    $img =  get_the_post_thumbnail( $post->ID, 'medium' );
    $snippet = get_post_meta($post->ID, 'Snippet', true);
    $return .= '<article class="col-lg-'.$width.' col-md-'.$width.' col-sm-'.$width.'"><a href="'.$link.'"><header><div class="page-title-post">'.$title.'</div></header><div class="entry-content">'.$img.'<p class="snippet">'.$snippet.'</p></div></a></article>';
} 

It says: Parse error: syntax error, unexpected '}' in ...

What am I doing wrong?

  • 1
    PHP error messages contain line numbers, that should indicate where it expects a closing brace. Indent your code correctly and it'll be more obvious where the problem is, and use a decent text editor/IDE that lets you do syntax checking inline rather than through trial and error – Tom J Nowell Mar 15 '17 at 14:50
  • missing semicolons at the end of the lines where you set the width. – Michael Mar 15 '17 at 15:50
1

it may be easier than you thought. You're coding is missing endline apostrophes:

foreach ( $posts as $post ) {
    if ( is_sticky() ) {
        $width = '12'
    } else {
        $width = '4'
    };

should be

foreach ( $posts as $post ) {
    if ( is_sticky() ) {
        $width = '12';
    } else {
        $width = '4';
    };

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.