按用户输入的类别显示帖子的快捷码,无需插件

时间:2019-09-10 作者:Poonam Katpara

我创建了一个名为knw\\u shr\\u docs的自定义帖子。我正在尝试创建一个短代码,该代码应根据类别显示帖子互动程序,即:[知识共享帖子/u per\\u page=\'5\'文档/u cat=\'docs\']类别应由我添加。我尝试的代码:-

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\' );
请任何人告诉我哪里错了。提前谢谢你。

1 个回复
最合适的回答,由SO网友:Praveen 整理而成

请尝试以下代码。我想它可以帮助你。

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;
}
短代码:[knowledge_sharing cat="pant" posts_per_page="5"]

相关推荐

Shortcode to show the code

如何创建一个短代码(或类似的代码)来在页面的某个地方显示页脚?我试过了,但没有结果。。。function show_footer() { return get_footer(); } add_shortcode( \'show_f\', \'show_footer\' ); 或者这个。。。function show_footer() { get_footer(); } add_shortcode( \'show_f\', \'sho