1

i am created a custom post called knw_shr_docs. i am trying to create a short code whcih should display post tile according to category i.e : [knowledge_sharing posts_per_page='5' doc_cat='docs'] category should be add by me. Code i tried :-

function func_knowledge_sharing_docs(){
    $a = shortcode_atts( array(
    'doc_cat'  =>  ''
), $atts );

$output = '';
$post_cat = esc_attr($a['doc_cat']);


$args = array(
    'category' => $post_cat,
    'post_type' => 'knowledgeSharingDocs',
    'order'  => 'DESC'
);

$query = new WP_Query( $args );

    $pages              = $query->posts;
    $output .= '<ul>';
    foreach($pages as $page) {
    $page_title     =   $page->post_title;
    $page_url           = get_page_link( $page->ID );


        $output .= '<li><a href="'.$page_url.'">' .$page_title. '</a></li>';

        }
        $output .= '</ul>';
    wp_reset_postdata();
    return $output;
}

add_shortcode( 'knowledge_sharing', 'func_knowledge_sharing_docs' );

please anyone tell where is my mistake. Thank you in advance.

0

Try the below code. I think it could help you.

add_shortcode( 'knowledge_sharing', 'cat_post' );

function cat_post($atts){

    // attributes for shortcode
   if (isset($atts['cat'])) {$cats = $atts['cat'];} else {return;}
   if (isset($atts['posts_per_page'])) {$posts_per_page = $atts['posts_per_page'];} else {$posts_per_page = -1;}

   // get the category posts
   $category = get_category_by_slug($cat);
   if (!is_object($category)) {return;}
   $args = array(
        'cat' => $category->term_id,
        'posts_per_page' => $posts_per_page,
        'post_type' => 'knowledgeSharingDocs',
        'order'  => 'DESC'
   );
   $posts = get_posts($args);

   // create the list output
   if (count($posts) > 0) {
       foreach ($posts as $post) {
           $link = get_permalink($post->ID);
           $title = $post->post_title;
           $image = get_the_post_thumbnail($post->ID, 'thumbnail');
           $output .= '<div id="postrow-'.$post->ID.'" class="postrow">';
           $output .= '<a class="postlink" href="'.$link.'">'.$image;
           $output .= '<h5 class="posttitle">'.$title.'</h5></a></div>';
       }
   return $output;
}

shortcode: [knowledge_sharing cat="pant" posts_per_page="5"]

  • i tried this but its not working – Poonam Katpara Sep 10 at 7:38
  • are you getting any error? – Pullata Praveen Sep 10 at 7:39
  • i think this shoul be $cats ? $category = get_category_by_slug($cats); – Poonam Katpara Sep 10 at 7:41
  • error:- your site is facing technical difficulties – Poonam Katpara Sep 10 at 7:41
  • 1
    yes i did it . thanx but. – Poonam Katpara Sep 23 at 9:06

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.