【问题标题】:How to convert shortcode to widget?如何将简码转换为小部件?
【发布时间】:2022-07-30 02:07:20
【问题描述】:

我有一个包含多个参数的简码,像这样


function recentpost_shortcode($atts, $content = null) { 
    global $post;   
    extract(shortcode_atts(array(
        'post_type' => '',
        'headline_get' => '',
        'cat'     => '',
        'style'     => '',
        'num'     => '5',
        'order'   => 'DESC',
        'orderby' => 'date',
    ), $atts));     
    $args = array(
        'post_type' => $post_type,
        'cat'            => $cat,
        'posts_per_page' => $num,
        'order'          => $order,
        'orderby'        => $orderby,
        'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 ),
    );  
    $output = '';
    $posts = get_posts($args);  
    $output .='<ul>';       
    foreach($posts as $post) {      
        setup_postdata($post);
        $output .='<li>'.esc_attr( get_the_title() ).'</li>';
    }
    
    $output .='</ul>';      
    wp_reset_postdata();    
    return  $output;    
}
add_shortcode('recentpost', 'recentpost_shortcode');

用于在网站上显示文章 我想把它变成一个小部件 这可能吗?如何? 谢谢

【问题讨论】:

  • 可以将此代码转换为小部件,是的。您是否查看过有关开发 WordPress 小部件的官方文档?如果没有,那么这可能会有所帮助:Widgets API.

标签: wordpress wordpress-shortcode


【解决方案1】:

听起来您想将短代码 [re​​centpost] 转换为小部件,对吗?此代码尚未经过测试,但它应该为您提供一个起点。基本上,你注册了这个小部件,然后你在公共函数下调用短代码(do_shortcode)。

//first register the widget (I am calling it recentpost_widget)
function recentpost_load_widget() {
  register_widget( 'recentpost_widget' );
}  
add_action( 'widgets_init', 'recentpost_load_widget' ); 

//Next We Create the Widget by Extending the current WP Class
class recentpost_widget extends WP_Widget { 
  function __construct() {
    parent::__construct( 
     // Base ID of your widget
     'recentpost_widget',  
     // The widget name that will appear in UI
     __('Recent Posts', 'recentpost_widget_domain'),  
     // Widget description
     array( 'description' => __( 'Displays Most Recent Posts','recentpost_widget_domain' ), ));
} 

// Creating the widget front-end (what the user views) Using Your Short Code
public function widget( $args, $instance ) {
    echo do_shortcode( '[recentpost]');     
}
 
} // Class recent_widget ends here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 2020-10-22
    相关资源
    最近更新 更多