• Resolved rikardo85

    (@rikardo85)


    Hello,

    I currently have a shortcode that can display a list of posts (custom post types)

    I have added a couple of attributes that if used display with no problems.

    How can I add the post’s title, id and category as attributes?

    Code I’m using within the shortcode function:

    extract( shortcode_atts( array(
    		'posts' => -1,
    		'order' => ''
    	), $atts ) );
    
            $args = array(
             'posts_per_page' => $posts,
             'order' => $order,
             'post_type' => 'mws_faqs'
            );
    
        $query = new WP_Query( $args );
    	while ( $query->have_posts() ) : $query->the_post(); ?>
              <div>
    		<h3><?php echo the_title(); ?></h3>
    	  </div>
    	  <?php endwhile;
              wp_reset_postdata(); ?>

    Any help much appreciated

Viewing 4 replies - 1 through 4 (of 4 total)
  • Just to be clear, you want the user to be able to specify the post title, id or category as a shortcode attribute and have it affect the output accordingly?

    Thread Starter rikardo85

    (@rikardo85)

    karpstrucking,

    Thanks for replying.

    That’s exactly what I’m looking to do.

    Okay. You’ll need to update the array in the shortcode_atts() to include the new attributes and their default values if not specified by the user:

    shortcode_atts( array(
      'posts' => -1,
      'order' => '',
      'title' => '',
      'id' => '',
      'category' => ''
    ), $atts ) );

    The Loop doesn’t allow for searching by title, so we’ll need to look up the post id when that is used:

    if ( $title ) {
      $post = get_page_by_title( $title, OBJECT, 'mws_faqs' );
      $id = $post->ID;
    }

    Then update your $args array to include the $id:

    $args = array(
      'posts_per_page' => $posts,
      'order' => $order,
      'post_type' => 'mws_faqs',
      'p' => $id,
      'cat' => $category
    );
    Thread Starter rikardo85

    (@rikardo85)

    Thank you so much!

    Works a treat 🙂

    Thanks again

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Add custom post type title and category to shortcode attribute’ is closed to new replies.