【问题标题】:Wordpress - How to get the information of a widget instanceWordpress - 如何获取小部件实例的信息
【发布时间】:2020-09-21 11:17:18
【问题描述】:

我想知道如何获取小部件实例的信息,以便能够从另一个小部件获取其所有信息。尝试 Get Widget ID 插件,但它返回“temp”,我也尝试使用此代码块:

https://wordpress.stackexchange.com/questions/240327/how-to-access-widget-data-from-outside-widget

但我仍然得到相同的结果。

我的想法如下:

我正在修改一个 Wordpress 小部件,以便它选择一个静态帖子,以实现数字报纸中特色帖子的功能......该小部件已经修改并且已经在工作。同一个小部件在我网站的多个地方重复出现,也就是说,我多次使用它(每次都有不同的选定帖子)。

我的想法是使用该小部件(由编辑器选择的那些)显示精选帖子并修改另一个小部件,该小部件向我显示除了在这些小部件中选择的帖子之外的所有帖子。为此,我想知道如何获取选择精选帖子的所述小部件的实例,以便能够在每个小部件中获取所选帖子的 ID,并显示除已作为精选帖子的帖子之外的所有帖子。

总而言之……我只是不想再看到被选为精选的新闻。

澄清:这不是我写的小部件,它是我购买的模板,由于它没有此功能,我正在尝试创建它。

我留下我的小部件的代码,以防它有任何用处:

<?php
if ( ! defined( 'ABSPATH' ) ) exit;
add_action('widgets_init', 'seleccion_subtitulo');

function seleccion_subtitulo() {
    register_widget('seleccion_subtitulo');
}

class seleccion_subtitulo extends WP_Widget {

/*-----------------------------------------------------------------------------------*/
/*  Widget Setup
/*-----------------------------------------------------------------------------------*/

    public function __construct() {
        $widget_ops = array(
            'classname' => 'seleccion_subtitulo',
            'description' => esc_html__('Seleccionar noticia con titulo y subtitulo', 'disto')
        );
        parent::__construct('seleccion_subtitulo', esc_html__('Noticias: Noticia titulo + subtitulo [Estilo 1]', 'disto'), $widget_ops);
    }

/*-----------------------------------------------------------------------------------*/
/*  Display Widget
/*-----------------------------------------------------------------------------------*/

function widget($args, $instance) {
    extract($args);

    $featured_post = isset($instance["featured_post"]) ? $instance["featured_post"] : '';
    $posts = null;
    $args =  array(
    'p'                => $featured_post,
    'posts_per_page'   => 1,
    'orderby'          => 'date',
    'order'            => 'DESC',
    'post_type'        => 'post',
    'post_status'      => 'publish',
    'ignore_sticky_posts' => true
    );

    $posts_query = new WP_Query;
    $posts = $posts_query->query($args);
    $unique_block_id = rand(10000, 900000);

    echo '<div class="jl_large_builder jl_nonav_margin jelly_homepage_builder jl-post-block-'.esc_html($unique_block_id).'">';
    if (!empty($instance['titles'])) {?>
<div class="homepage_builder_title">
    <h2 class="builder_title_home_page">
        <?php echo esc_attr($instance["titles"]);?>
    </h2>
</div>
<?php }?>
<?php
    while ($posts_query->have_posts()) {
       $post_id = get_the_ID();
       $posts_query->the_post();
       $categories = get_the_category(get_the_ID());
    ?>
<div class="jl_post_title_top jl_large_format">       
    <h3 class="image-post-title"><a href="<?php the_permalink(); ?>">
            <?php the_title()?></a></h3>
</div>
<div class="post-entry-content">
    <div class="post-entry-content-wrapper">
        <div class="large_post_content">
            <p>
               <?php echo wp_trim_words( get_the_content(), 34, '...' );?>
            </p>
            <!-- <div class="jl_large_sw">
             <a href="<?php the_permalink();?>" class="jl_large_more"><?php echo esc_html__('Read More', 'disto')?></a>             
            <?php if(function_exists('disto_share_footer_link')){echo disto_share_footer_link(get_the_ID());}?>
            </div> -->
        </div>
    </div>
</div>
<div class="box jl_grid_layout1 blog_large_post_style">
<?php if ( has_post_thumbnail()) {?>
<div class="jl_front_l_w">
<?php $slider_large_thumb_id = get_post_thumbnail_id();
    $slider_large_image_header = wp_get_attachment_image_src( $slider_large_thumb_id, 'disto_slider_grid_large', true ); ?>
    <?php if($slider_large_thumb_id){?>
    <span class="image_grid_header_absolute" style="background-image: url('<?php echo esc_url($slider_large_image_header[0]); ?>')"></span>
    <?php }else{?>
    <span class="image_grid_header_absolute"></span>
    <?php }?>
    <a href="<?php the_permalink(); ?>" class="link_grid_header_absolute" title="<?php the_title_attribute(); ?>"></a>
 <?php if(get_theme_mod('disable_post_category') !=1){
      $categories = get_the_category(get_the_ID());          
      if ($categories) {
        echo '<span class="meta-category-small">';
        foreach( $categories as $tag) {
          $tag_link = get_category_link($tag->term_id);
          $title_bg_Color = get_term_meta($tag->term_id, "category_color_options", true);
          $title_reactions = get_term_meta($tag->term_id, "disto_cat_reactions", true);
         if($title_reactions){}else{echo '<a class="post-category-color-text" style="background:'.$title_bg_Color.'" href="'.esc_url($tag_link).'">'.$tag->name.'</a>';}
        }echo "</span>";}}?>
<?php echo disto_post_type();?> 
</div>
<?php }?>
<div class="jl_post_title_top jl_large_format">       
    <?php echo disto_single_post_meta(get_the_ID()); ?>
</div>
</div>
<?php }
        if($post_loadmore == 1){echo '<div class="jl-loadmore-btn-w"><a href="#" class="jl_btn_load">'.esc_html__('Load more', 'disto').'</a></div>';
        wp_add_inline_script( 'disto-custom', "(function($){ $(document).ready(function() {'use strict'; var current_page_".esc_js($unique_block_id)." = 1; $('.jl-post-block-".esc_js($unique_block_id)." .jl_btn_load').click(function(e){ e.preventDefault(); e.stopPropagation(); var button = $(this), data = {'action': 'jl_post_more','query': ".json_encode( $posts_query->query_vars , true).",'page' : current_page_".esc_js($unique_block_id).",'cat' : '".esc_js($cats)."','jl_layout' : 'postslarge'}; var button_default_text = button.text(); $.ajax({ url : '".esc_url(site_url())."/wp-admin/admin-ajax.php', data : data, type : 'POST', beforeSend : function ( xhr ) {button.text('');button.addClass('btn-loading'); }, success : function( data ){ if( data ) { button.text( button_default_text ); button.removeClass('btn-loading'); $('.jl-post-block-".esc_js($unique_block_id)." .jl-loadmore-btn-w').before(data); current_page_".esc_js($unique_block_id)."++; if ( current_page_".esc_js($unique_block_id)." == ".esc_js($posts_query->max_num_pages)." ) button.remove(); }else {button.remove();}}});});});})(jQuery);");
        }
        wp_reset_postdata();
?>
</div>
<?php }
/*-----------------------------------------------------------------------------------*/
/*  Update Widget
/*-----------------------------------------------------------------------------------*/

function update( $new_instance, $old_instance ) {
    $instance = $old_instance;
    $instance['featured_post'] = $new_instance['featured_post'];
    return $instance;
}

/*-----------------------------------------------------------------------------------*/
/*  Widget Settings (Displays the widget settings controls on the widget panel)
/*-----------------------------------------------------------------------------------*/

function form( $instance ) {?>

<h2>Elige una de las ultimas 20 noticias para establecerla como portada secundaria.</h2>
<div class="container">
    <p>
        <label>
            <strong> <?php esc_html_e('Seleccionar noticia destacada:', 'disto');?></strong>
        </label>
    </p>
    <p>    
        <select id="<?php echo esc_attr( $this->get_field_id( 'featured_post' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'featured_post' ) ); ?>">

            <?php 
                $posts_args = array('posts_per_page' => 20,
                'orderby'          => 'date',
                'order'            => 'DESC',
                'post_type'        => 'post',
                'post_status'      => 'publish',
                'ignore_sticky_posts' => true);


                $last_entries = get_posts($posts_args);
                foreach ($last_entries as $entry) {
            ?>
                <option value="<?php echo $entry->ID; ?>" <?php if($instance['featured_post']==$entry->ID){ echo 'selected="selected"'; } ?> ><?php echo $entry->post_title; ?></option>
            <?php
                }
            ?>
        </select>
    </p>
</div>

<?php
    }
}
?>

如果我执行 var_dump ($instance),它会显示以下内容:

array(3) { ["featured_post"]=> string(4) "2970" ["so_sidebar_emulator_id"]=> string(29) "seleccion_subtitulo-421210000" ["option_name"]=> string(26) "widget_seleccion_subtitulo" }

我估计以下值告诉我我的小部件实例的 ID:

["so_sidebar_emulator_id"] => string (29) "seleccion_subtitulo-421210000"

但我不知道如何从另一个小部件调用它,以从中获取信息。


在获取该信息时,我尝试使用以下代码来查看我得到了什么(我在首先出现的链接中看到了此代码):

$widget_name = 'seleccion_subtitulo';
$widget_instance = '421210000';
$widget_instances = get_option('widget_' . $widget_name);
$data = $widget_instances[$widget_instance];
var_dump($widget_instances);

如果我这样做 var_dump($data); 我会得到 NULL

如果我这样做 var_dump($widget_instances); 我会得到:

array(1) { ["_multiwidget"]=> int(1) }

【问题讨论】:

  • 嗨,Joaquin,听起来您想要为您编写代码,这不是堆栈的意义所在。请参阅:stackoverflow.com/help/on-topic。我建议显示你到目前为止的代码,在每一步尝试调试输出,这样你就可以看到你可能已经出错的地方,你是否有正确的小部件名称等,它是否获取了数据库中的内容,是小部件实际上在数据库中??数据有什么结构?一旦有了小部件数据的数据结构,就可以将帖子 ID 提取到数组中。然后你可以做一个不包括那些帖子ID的查询。
  • @anmari 你好,代码不是我写的……我只是想问是否有一种方法可以获取正在使用的小部件实例的 ID……我估计是Wordpress一般的东西,所以才问。现在我编辑帖子并显示我正在使用的小部件的代码,但我认为这无关紧要,因为我对小部件本身不感兴趣,但如何从另一个小部件获取它的数据......这就是我问的原因实例,一旦我得到实例,我就有了我查阅的小部件的数据。

标签: php wordpress widget instance


【解决方案1】:

让我们将您的问题重新表述为两部分:

  1. “如何获取小部件设置”
  2. “如何获取该小部件使用的精选帖子列表,以便将它们从另一个帖子列表中排除”

1.小部件设置: 小部件设置存储在 wp_options 表中的数据库中。如果您在选项名称字段中使用 widget% 通配符在 phpmyadmin 中进行搜索,您将看到所有小部件及其序列化数据数组。

您可能会注意到它们都有一个名为“_multiwidget”的子数组,其中包含实例及其设置。在上面的示例中,您转储了此 ["_multiwidget"]=&gt; int(1)

这表明该小部件尚未存储任何内容。小部件不在侧边栏中和/或没有为该小部件定义精选帖子。

如果小部件已通过某些设置保存到侧边栏,我们将在此处看到更多详细信息。

设置一些小部件实例,以便您可以查看保存的数据结构。然后您将能够看到小部件的详细信息(通过 phpmyadmin 或像以前一样通过转储)

2。从一组小部件实例中获取精选帖子列表,以便将它们从查询中排除(在另一个小部件中)

对于您查看的小部件,我们可能会看到一组设置,其中一个称为“featured_post”。

一旦小部件被拖到一些侧边栏并在少数情况下定义了一些特色帖子,您就可以在新小部件中执行类似(伪代码)的操作:

$widget_name = 'seleccion_subtitulo'; //if that's the widget name in the db.
$widget_settings = get_option('widget_' . $widget_name);
$featured_posts = array();
if (!empty($widget_settings)) {
    if (!empty($widget_settings["_multiwidget"])) {
        $instances = $widget_settings["_multiwidget"];
        foreach ( $instances as $wid =>  $instance) {
            $featured_posts[] = $instance['featured_post']; // if that is how it is stored in the widget details
        }
    }
}

然后您可以使用 https://developer.wordpress.org/reference/functions/get_posts/ 并传递数组 $featured_posts 在参数数组中作为

'exclude' => $featured_posts 

请注意,对于您想要实现的目标,不必知道“实例”或“小部件 ID”,只需遍历该小部件的所有实例即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 2020-07-14
    • 1970-01-01
    • 2011-10-12
    • 2015-11-16
    • 2022-06-11
    • 1970-01-01
    相关资源
    最近更新 更多