web-dev-qa-db-fra.com

Modification des fonctions WP_LIST_AUTHORS pour afficher tous les utilisateurs dans une grille (et une pagination)

Le titre dit tout.

Je prends WP_LIST_AUTHOR et le modifie pour créer plus d'un répertoire de membres qu'une liste d'auteurs tout en conservant intactes les options d'origine (et je vais en ajouter d'autres ultérieurement). Ma première tâche a été d’intégrer la pagination, ce que j’ai réussi à faire (code ci-dessous) [même si ce n’est pas encore très joli].

Je souhaite maintenant que cette information soit intégrée dans des tableaux (probablement 15 résultats par page, dans une grille de 3x5. Cellule de cellule en rangée, cellule de cellule en rangée, etc.). Je ne suis pas vraiment sûr de la meilleure façon de faire cela, ou si cela peut même être fait avec la façon dont le code est construit, tout conseil ou toute ressource liée serait grandement apprécié! Je suis vraiment en train de pirater des choses ensemble;) Notez également; le site utilise le plugin s2member et tout code ne devra pas être dérangé par cette fonctionnalité.

<?php

///////////////////////
/////  SEXY TIME  /////
///////////////////////

/** 
 * CUSTOM FUNCTIONS BY DUIWEL
 * We are taking the regular wp_list_authors and forcing it to always display all
 * the authors, as well as have pagination and a better format
 *
 * This is my first attempt at a Wordpress Hack such as this
 * 
 * 5/28/2011
 *
 * I have left most of the original function text intact, including the comments below
 *
 * I used a lot of code from Crayon Violent at PHPFREAKS
 * http://www.phpfreaks.com/tutorial/basic-pagination
 * Most of his/her comments also remain intact
 *
 */


//ORIGINAL WP COMMENTS for wp_list_authors
/**
 * List all the authors of the blog, with several options available.
 *
 * <ul>
 * <li>optioncount (boolean) (false): Show the count in parenthesis next to the
 * author's name.</li>
 * <li>exclude_admin (boolean) (true): Exclude the 'admin' user that is
 * installed bydefault.</li>
 * <li>show_fullname (boolean) (false): Show their full names.</li>
 * <li>hide_empty (boolean) (true): Don't show authors without any posts.</li>
 * <li>feed (string) (''): If isn't empty, show links to author's feeds.</li>
 * <li>feed_image (string) (''): If isn't empty, use this image to link to
 * feeds.</li>
 * <li>echo (boolean) (true): Set to false to return the output, instead of
 * echoing.</li>
 * <li>style (string) ('list'): Whether to display list of authors in list form
 * or as a string.</li>
 * <li>html (bool) (true): Whether to list the items in html form or plaintext.
 * </li>
 * </ul>
 *
 * @link http://codex.wordpress.org/Template_Tags/wp_list_authors
 * @since 1.2.0
 * @param array $args The argument array.
 * @return null|string The output, if echo is set to false.
 */

 //THE FUNCTION

function duiwel_custom_list_users($args = '') {
    global $wpdb;



    // HIDE_EMPTY ORIGINALLY TRUE, now FALSE
    $defaults = array(
        'orderby' => 'name', 'order' => 'ASC', 'number' => '',
        'optioncount' => false, 'exclude_admin' => true,
        'show_fullname' => false, 'hide_empty' => false,
        'feed' => 'feed', 'feed_image' => '', 'feed_type' => 'rss2', 'echo' => true,
        'style' => 'list', 'html' => true
    );

    $args = wp_parse_args( $args, $defaults );
    extract( $args, EXTR_SKIP );

    $return = '';

    $query_args = wp_array_slice_assoc( $args, array( 'orderby', 'order', 'number' ) );
    $query_args['fields'] = 'ids';
    $authors = get_users( $query_args );

    // FYI This is the post count of each author, not the total count of authors
    $author_count = array();
    foreach ( (array) $wpdb->get_results("SELECT DISTINCT post_author, COUNT(ID) AS count FROM $wpdb->posts WHERE post_type = 'post' AND " . get_private_posts_cap_sql( 'post' ) . " GROUP BY post_author") as $row )
        $author_count[$row->post_author] = $row->count;

        // need to count 'authors' here
        $totalusers = count($authors);

        //////////////////////////////
        ////// PAGINATION ////////////
        //////////////////////////////

        $numrows = $totalusers;

        // number of rows to show per page
        $rowsperpage = 10;
        // find out total pages
        $totalpages = ceil($numrows / $rowsperpage);

        // get the current page or set a default
        if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
        // cast var as int
        $currentpage = (int) $_GET['currentpage'];
        } else {
        // default page num
        $currentpage = 1;
        } // end if


        // if current page is greater than total pages...
        if ($currentpage > $totalpages) {
        // set current page to last page
        $currentpage = $totalpages;
        } // end if
        // if current page is less than first page...
        if ($currentpage < 1) {
        // set current page to first page
        $currentpage = 1;
        } // end if

        // the offset of the list, based on current page 
        $offset = ($currentpage - 1) * $rowsperpage;



        //////////////////////////////
        ////// END PAGINATION ////////
        //////////////////////////////


        //////////////////////////////////////////
        ////// PAGINATION TO FOLLOW ARRAY  ///////
        //////////////////////////////////////////


        //I need to take the SQL LIMIT function from the pagination code I found
        //and incorporate it into the arrays I'm using, cause I'm not actually
        //querying a SQL table, I'm querying an array

        $pagination_user_table = $authors;

        $paged_authors = array_slice( $pagination_user_table , $offset , $rowsperpage );

        //////////////////////////////////////////
        ////// START NORMAL WP_LIST_AUTHOR  ////////
        //////////////////////////////////////////


    foreach ( $paged_authors as $author_id ) {
        $author = get_userdata( $author_id );

        if ( $exclude_admin && 'admin' == $author->display_name )
            continue;

        $posts = isset( $author_count[$author->ID] ) ? $author_count[$author->ID] : 0;

        if ( !$posts && $hide_empty )
            continue;

        $link = '';

        if ( $show_fullname && $author->first_name && $author->last_name )
            $name = "$author->first_name $author->last_name";
        else
            $name = $author->display_name;

        if ( !$html ) {
            $return .= $name . ', ';

            continue; // No need to go further to process HTML.
        }

        if ( 'list' == $style ) {
            $return .= '<li>';
        }

        //some extra Avatar stuff

        $avatar = 'wavatar';
        $link = get_avatar($author->user_email, '80', $avatar);



        $link .= '<div id=directoryinfo>' . ' <a href="' . get_author_posts_url( $author->ID, $author->user_nicename ) . '" title="' . esc_attr( sprintf(__("Posts by %s"), $author->display_name) ) . '">' . $name . '</a>';

        if ( !empty( $feed_image ) || !empty( $feed ) ) {
            $link .= ' ';
            if ( empty( $feed_image ) ) {
            //Line breaking for RSS formatting (testing mostly)
                $link .= '<br>(';
            }

            $link .= '<a href="' . get_author_feed_link( $author->ID ) . '"';

            $alt = $title = '';
            if ( !empty( $feed ) ) {
                $title = ' title="' . esc_attr( $feed ) . '"';
                $alt = ' alt="' . esc_attr( $feed ) . '"';
                $name = $feed;
                $link .= $title;
            }

            $link .= '>';

            if ( !empty( $feed_image ) )
                $link .= '<img src="' . esc_url( $feed_image ) . '" style="border: none;"' . $alt . $title . ' />';
            else
                $link .= $name;

            $link .= '</a>';

            if ( empty( $feed_image ) )
                $link .= ')';
        }

        if ( $optioncount )
            $link .= ' ('. $posts . ')';

        $return .= $link;
        $return .= ( 'list' == $style ) ? '</li>' : ', ';
    }






    $return = rtrim($return, ', ');

    if ( !$echo )
        return $return;

    echo $return;

        /////////////////////////////////////////
        ////// END WP_LIST_AUTHOR NORMALCY //////
        /////////////////////////////////////////

    // little spacer
    echo "<br /><br />";
        //////////////////////////////
        ////// PAGINATION LINKS //////
        //////////////////////////////



/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1

   echo " <a href=' " , the_permalink() , " ?currentpage=1'><<</a> ";

   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page

      echo " <a href=' " , the_permalink() , " ?currentpage=$prevpage'><</a> ";



} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
        echo " <a href=' " , the_permalink() , " ?currentpage=$x'>$x</a> ";


      } // end else
   } // end if 
} // end for

// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 

            echo " <a href=' " , the_permalink() , " ?currentpage=$nextpage'>></a> ";

   // echo forward link for lastpage

            echo " <a href=' " , the_permalink() , " ?currentpage=$totalpages'>>></a> ";


} // end if
/****** end build pagination links ******/


        //////////////////////////////////
        ////// END PAGINATION LINKS //////
        //////////////////////////////////


}





///////////////////////////
/////  END SEXY TIME  /////
///////////////////////////



?>

            <div id="directorylist">
<ul>
<?php duiwel_custom_list_users() ?>
</ul>
        </div><!-- #directorylist -->
3
Sam K

Votre extrait est un peu trop verbeux à suivre (et il est tard ici), donc c'est plutôt une prise alternative. Je pense que falsifier wp_list_author() pourrait être excessif ici. Il serait plus élégant d’accrocher à la recherche d’utilisateur et de découper avec précision la portion d’auteurs dont vous avez besoin.

Voici un exemple de code que j'ai créé:

add_action('pre_user_query','offset_authors');

$authors_per_page = 1;
$current_page = absint(get_query_var('page'));

function offset_authors( $query ) {

    global $current_page, $authors_per_page;

    $offset = empty($current_page) ? 0 : ($current_page - 1) * $authors_per_page;    
    $query->query_limit = "LIMIT {$offset},{$authors_per_page}";
}

wp_list_authors();

Vérifiez également paginate_links() la fonction de construction de la pagination.

1
Rarst