Including a custom post type in the Archives widget

I have a custom post type called “videos” that I want to include in the Archives widget (stock widget in the TwentyTwelve theme). It DOES already appear on the archives page, but just not in the widget.

I already have

add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
function add_my_post_types_to_query( $query ) {
if ( $query->is_main_query() )
    $query->set( 'post_type', array( 'post', 'videos' ) );
return $query;
}

in functions.php – can I modify the IF statement to be something like “if main query OR archive widget query”? How can I do this?

Solutions Collecting From Web of "Including a custom post type in the Archives widget"

The Archive widget is using wp_get_archives() to display the archive.

If you want to target all the wp_get_archives() functions, you can use the getarchives_where filter to add your custom post type:

add_filter( 'getarchives_where', 'custom_getarchives_where' );
function custom_getarchives_where( $where ){
    $where = str_replace( "post_type = 'post'", "post_type IN ( 'post', 'videos' )", $where );
    return $where;
}

If you want to target only the first Archive widget, you can try

add_action( 'widget_archives_args', 'custom_widget_archives_args' );
function custom_widget_archives_args( $args ){
    add_filter( 'getarchives_where', 'custom_getarchives_where' );
    return $args;
}

with

function custom_getarchives_where( $where ){
    remove_filter( 'getarchives_where', 'custom_getarchives_where' );
    $where = str_replace( "post_type = 'post'", "post_type in ( 'post', 'videos' )", $where );
    return $where;
}

where the filter is removed, to prevent affecting other parts.

It worked for me:

class CPT_Archives extends WP_Widget
{
    function widget()
    {
        ...

        add_filter('getarchives_where', array($this, 'getarchives_where_filter'), 10, 2);

        $args = array(
            'format' => 'option',
            'echo'   => false,
        );
        $options = wp_get_archives($args);
        $options = str_replace('?m=', '?post_type=CPT&m=', $options);

        echo '<select name="CPT_archive-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">';
        echo '  <option value="">' . esc_attr( __( 'Select Month' ) ) . '</option>';
        echo $options;
        echo '</select>';

        ...

    }

    function getarchives_where_filter($where)
    {
        $where = str_replace( "post_type = 'post'", "post_type = 'CPT'", $where );
        return $where;
    }
}