create shortcodes for posts

时间:2017-06-19 作者:Abuzer kıllıbacak

$query = new WP_Query(array(
\'post_type\' => \'my_posttype\',
\'post_status\' => \'publish\',
\'posts_per_page\' => -1,
\'orderby\' => \'title\',
\'order\' => \'ASC\'
));

while ($query->have_posts()) {
    $query->the_post();
    $shortcodename = __to_eng(get_the_title());
    $shortcodefuncname = $shortcodename.\'_shortcode\';
    $img24x24 = get_the_post_thumbnail_url(\'24x24\');
    $shortcodefuncname = function(){
        global $shortcodename;
        return $sortcodename;
    };
    add_shortcode($shortcodename, $shortcodefuncname);
}
wp_reset_query();
这是我的帖子短码代码。当我试着按那个快捷码[我想要的我的帖子]时,它会返回我的最后一篇帖子。怎么了?

1 个回复
SO网友:Bikash Waiba

你的shortcode 名称和shotrcode_function_name 是动态的,即随帖子名称的变化而变化,如果两篇帖子的标题相同,则会导致问题。此外,您可能不知道或困惑什么shortcodes 可用。如果你的帖子标题总是唯一的,我建议你这样做。

while ($query->have_posts()) {
    $query->the_post();

    $shortcodename = strtolower( __to_eng(get_the_title()) ); 
    str_replace(\' \', \'_\', $shortcodename); // your post name, replaced white space  with \'_\'
    $shortcodefuncname = $shortcodename.\'_shortcode\'; // available shortcodes
    $img24x24 = get_the_post_thumbnail_url(\'24x24\');

    $attribute = array(\'post_id\' => get_the_ID(), \'post_title\' => get_the_title(), \'image_url\'=>$img24x24, \'post_content\' => get_the_content());

    $shortcode[\'attribute\'] = $attribute;
    $shortcode[\'func_name\'] = $shortcodefuncname;
    $shortcode[\'shortcode_name\'] = $shortcodename;
    $shoortcodes[] = $shortcode;

}
wp_reset_query();


foreach ( $shortcodes as $shortcode ){
     function $shortcode[\'func_name\']( $atts ){
     $atts = shortcode_atts( array(  //defaults atts for shortcode
           \'image\' => \'show\',
           \'content\' => \'show\'
          ), $atts );
          $return = \'<h3>\'.$shortcode[\'attribute\'][\'post_title\'].\'</h3>\';
          if( !($atts[\'image\']==\'hide\') ){ // you can set image="hide" in shortcode
              $return .= \'<img src="\'.$shortcode[\'attribute\'][\'image_url\'].\'"/>\';
          }  
          if( !($atts[\'content\']==\'hide\') ){
             $return .= \'<p>\'.$shortcode[\'attribute\'][\'post_content\'].\'</p>\';
           }
           return $return;         

     }
     add_shortcode($shortcode[\'shortcode_name\'], $shortcode[\'func_name\']);
}
您的短代码已准备就绪。您可以使用

[my_post_which_i_want] // my_post_which_i_want is post title lowercased and white space replaced with \'_\'

结束

相关推荐

从WordPress外部获取ShortCode属性

有没有一种干净的方法可以在Wordpress的默认行为之外获取短代码的属性值?我正在Wordpress安装之外编写一个脚本include(\'../wp-load.php\'); 在一开始。就我而言,我希望\"caption\" 属性[caption] shortcode 我发现最好的方法如下,但我对此很不满意。原帖子内容:[caption id=\"attachment_1\" align=\"alignleft\" width=\"150\" caption=\"I\'m a wicked cool