【问题标题】:Wordpress custom demo sidebar not appearing on postsWordpress 自定义演示侧边栏未出现在帖子上
【发布时间】:2020-11-11 13:30:04
【问题描述】:

以下 php 文件获取自定义演示侧边栏以显示在管理小部件菜单中,但不显示在实际帖子中(文件位于同名文件夹中,位于 WP 文件目录中的插件文件夹中)– 添加文本小部件到自定义侧边栏进行测试:

<?php

/**
* Plugin Name:    Single Post CTA
* Plugin URI:     https://github.com/cdils/single-post-cta
* Description:    Adds sidebar (widget area) to single posts
* Version:        0.1
* Author:         Carrie Dils
* Author URI:     https://carriedils.com
* License:        GPL v2+
* License URI:    https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain:    spc
*/

// If this file is called directly, abort
if ( !defined( 'ABSPATH' ) ) {
  die;
}

/**
* Load stylesheet
*/

function spc_load_stylesheet() {
  if ( is_single() ) {
    wp_enqueue_style( 'spc_stylesheet', plugin_dir_url(__FILE__) .'spc-styles.css' );
  }
}

// Hook stylesheet
add_action( 'wp_enqueue_scripts', 'spc_load_stylesheet' );

// Register a custom sidebar
function spc_register_sidebar() {
      register_sidebar( array(
        'name'          => __( 'Single Post CTA', 'spc' ),
        'id'            => 'spcsidebar',
        'description'   => __( 'Displays widget area on single posts', 'spc' ),
        'before_widget' => '<div class="widget spc">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="widgettitle spc-title">',
        'after_title'   => '</h2>',
   ) );
}

// Hook sidebar
add_action( 'widgets_init', 'spc_register_sidebar' );

// Display sidebar on single posts
function spc_display_sidebar( $content ) {
    if ( is_single() ) {
      dynamic_sidebar( 'spcsidebar' );
    }
    return $content;
}

// Add dynamic sidebar
add_filter( 'the content', 'spc_display_sidebar' );

以下是与自定义侧边栏文件位于同一文件夹中的关联样式表:

.spc {
    background: gray;
    color: blue;
}

定制器下的小部件菜单显示“您的主题有 1 个其他小部件区域,但此特定页面不显示它”。这个WordPress指南https://developer.wordpress.org/themes/functionality/sidebars/似乎表明必须在主题或子主题的functions.php文件中注册侧边栏/小部件,然后创建一个sidebar-{name}.php文件来运行dynamic_sidebar函数。是不是这样?我正在使用 Genesis Sample 子主题,并切换到 2020 和 2017 的 wordpress 主题,或者停用所有其他插件都没有解决问题。

【问题讨论】:

    标签: php wordpress widget sidebar


    【解决方案1】:

    过滤器应该是add_filter( 'the_content', 'spc_display_sidebar' );。您忘记了下划线。

    如果您尝试在页面帖子类型中显示侧边栏,那么is_single() 将无法正常工作。请改用is_singular()

    【讨论】:

      【解决方案2】:

      Mistack 在钩子中不是“内容”,使用“the_content”

      例如。 add_filter('the_content', 'spc_display_sidebar');

      【讨论】: