Support » Fixing WordPress » wp_get_archives( ) for specific author?

  • Resolved nicolaelvin


    I have many members posting different posts. I need an archive that only shows the outputted archive months for that currently logged in user. However, I note that the $args doesn’t contain an option for this.

Viewing 6 replies - 1 through 6 (of 6 total)
  • Moderator keesiemeijer



    You can add filters to wp_get_archives().
    Call wp_get_archives() like this for logged in users:

     	if ( is_user_logged_in()) {
    		global $archive_author_id;
    		$archive_author_id = get_current_user_id();
    		// add the filter to wp_get_archives to filter it by user
    		add_filter( 'getarchives_where' , 'getarchives_where_filter');
    		// remove the filter
    		remove_filter( 'getarchives_where' , 'getarchives_where_filter');
    	} else {
    		// user is not logged in
    		echo 'You have to log in to see your personal archive';

    And put this in your theme’s functions.php:

    // alter the sql "where" query for montly archives
    function getarchives_where_filter( $where) {
    	global $archive_author_id;
    	return $where .' AND post_author = ' . $archive_author_id;
    // query monthly archives by user.
    function my_post_queries( $query ) {
    	// do not alter the query on wp-admin pages and only alter it if it's the main query
    	if (!is_admin() && $query->is_main_query()){
    		// alter the query for monthly archive pages
    		if(is_archive() && is_month()){
    			if ( is_user_logged_in()) {
    			  $user_nicename = get_userdata(get_current_user_id())->user_nicename;
    				$query->set('author_name', $user_nicename);
    				//$query->set('posts_per_page', 1);
    add_action( 'pre_get_posts', 'my_post_queries' );

    Thank you so much for this. I forgot to mention one thing though
    – the site adminhas a blog where it always gets their posts and their archives no matter which user is logged in. So I need to run a version on this page lets call it admin-blog-page, that gets the archives for user where username ==admin. However on user-blog-page, I just need to get current logged in user’s archive, as above.

    Can I run two different versions of above without affecting the other?

    I think I have worked it out. So if I am on admin-blog-page, I just set global $archive_author_id==adminsID.

    I’m getting this ‘warning’ and the archives it is outputting are for all users:

    Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'getarchives_where_filter' not found or invalid function name in '...\wp-includes\plugin.php on line 170

    ignore above error, I had forgotten to upload my functions.php!

    the above function fixes it. Thank you. I need to look into how to add filters to wordpress. Something I am clueless about.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘wp_get_archives( ) for specific author?’ is closed to new replies.