0
votes

Following php file gets a custom demo sidebar to show up in the admin widget menu, but not on actual posts (file located in folder with same name, which is located in the plugin folder in WP file directory) – add a text widget to custom sidebar to test:

<?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' );

Here is the associated style sheet located in the same folder as the file for the custom sidebar:

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

The widgets menu under customizer says “Your theme has 1 other widget area, but this particular page doesn’t display it”. This WordPress guide https://developer.wordpress.org/themes/functionality/sidebars/ appears to indicate that one has to register the sidebar/widget in the theme or child theme’s functions.php file and then create a sidebar-{name}.php file in which to run the dynamic_sidebar function. Is this the way instead? I’m using the Genesis Sample child theme, and switching to 2020 and 2017 wordpress themes, or deactivating all other plugins has not fixed problem.

2

2 Answers

1
votes

The filter should be add_filter( 'the_content', 'spc_display_sidebar' );. You forgot the underscore.

If you are trying to display the sidebar in a page post type thenis_single() is not going to work. Try is_singular()instead.

0
votes

Mistack is in hook not "the content", use "the_content"

Ex. add_filter( 'the_content', 'spc_display_sidebar' );