get_categories limite per mostrare ogni categoria una volta
-
16-10-2019 - |
Domanda
Sto cercando di creare una home page dove è un elenco di categorie con associato ad una miniatura per ogni. Vorrei così ritorna ogni categoria una volta e restituisce l'associato miniatura dalla ultimi messaggi, o meglio non mi richiede di aggiungere un Foto di presentazione per ogni post, ma afferra la miniatura dall'immagine del post, utilizzando post_mime_type ? Io sono ancora un modo fuori perché sta tornando la categoria per ogni post che è all'interno di quella categoria e quindi associando l'immagine con tutte le categorie.
Questa è la funzione con cui sto lavorando:
function home_filter() {
if ( is_home() )
{
add_filter( 'the_content', 'home_cats' );
}
}
add_action('template_redirect', 'home_filter');
function home_cats(){
$args=array(
'orderby' => 'name',
'order' => 'ASC',
);
$categories=get_categories($args);
foreach($categories as $category) {
echo '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . get_the_post_thumbnail($page->ID, 'thumbnail') . $category->name.'</a></li> ';
}
}
La home page è semplice:
<ul>
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content();?>
<?php endwhile; ?>
</ul>
L'output è qualcosa di simile:
<ul>
<li><a href="../?cat=1" title="View all posts in Cat A" ><img src="..image-A.jpg" />Cat A</a></li>
<li><a href="../?cat=3" title="View all posts in Cat B" ><img src="..image-A.jpg" />Cat B</a></li>
<li><a href="../?cat=1" title="View all posts in Cat A" ><img src="..image-B.jpg" />Cat A</a></li>
<li><a href="../?cat=3" title="View all posts in Cat B" ><img src="..image-B.jpg" />Cat B</a></li>
<li><a href="../?cat=1" title="View all posts in Cat A" ><img src="..image-C.jpg" />Cat A</a></li>
<li><a href="../?cat=3" title="View all posts in Cat B" ><img src="..image-C.jpg" />Cat B</a></li>
</ul>
Qualcuno può aiutarmi per favore a capire come restituire ogni categoria una sola volta e includono il pollice dal ultimi messaggi in quella categoria? E ancora meglio Qualcuno può pensare a un modo per ottenere questo risultato senza dover impostare l'immagine funzione ogni volta?
Soluzione
Normalmente mi piace a rifuggire da raccomandare SQL diretta, ma nel tuo caso d'uso penso che sia giustificata.
ho codificato questo come una query SQL diretta; come si può notare è un po 'complessa. È possibile copiare il seguente codice nel file functions.php
del vostro tema o aggiungerlo al file .php
di un plugin che si potrebbe aver scritto:
function home_cats($max_image_height=150){
$categories= get_taxonomy_latest_posts_with_attachment('category');
echo '<h1>Categories</h1>';
foreach($categories as $category) {
$category_link = get_category_link( $category->term_id );
$category_title = sprintf( __( "View all posts with category: '%s'" ),$category->term_name );
$post_title = get_the_title($category->post_id);
$post_link = get_permalink($category->post_id);
$img_html = wp_get_attachment_image( $category->attachment_id, array( 'thumbnail',$max_image_height ) );
$html = <<<HTML
<div id="category-{$category->term_slug}" class="category">
<span style="float:right;">{$img_html}</span>
<span style="float:left;">
<h2><a href="{$category_link}" title="{$category_title}">{$category->term_name}</a></h2>
<p style="float:left;">Latest post: <a href="{$post_link}" title="{$post_title}">$post_title</a></p>
</span>
</div>
<br clear="both" />
HTML;
echo $html;
}
}
function get_taxonomy_latest_posts_with_attachment($taxonomy) {
global $wpdb;
$sql =<<<SQL
SELECT
categorized_posts.rownum,
categorized_posts.term_id,
categorized_posts.term_name,
categorized_posts.term_slug,
categorized_posts.post_id,
categorized_posts.post_date,
categorized_posts.post_title,
attachments.ID AS attachment_id,
attachments.post_title AS attachment_title,
attachments.post_mime_type AS attachment_mime_type,
attachments.guid AS attachment_guid
FROM
(
SELECT
rownum,
term_id,
term_name,
term_slug,
post_id,
post_date,
post_title,
post_parent,
post_name,
post_type
FROM (
SELECT
IF( @prev <> {$wpdb->terms}.term_id, @rownum := 1, @rownum := @rownum+1 ) AS rownum,
@prev := {$wpdb->terms}.term_id,
{$wpdb->terms}.term_id,
{$wpdb->terms}.name AS term_name,
{$wpdb->terms}.slug AS term_slug,
{$wpdb->posts}.ID as post_id,
{$wpdb->posts}.post_date,
{$wpdb->posts}.post_title,
{$wpdb->posts}.post_parent,
{$wpdb->posts}.post_name,
{$wpdb->posts}.post_type
FROM
{$wpdb->term_taxonomy}
INNER JOIN {$wpdb->terms} ON {$wpdb->term_taxonomy}.term_id={$wpdb->terms}.term_id
INNER JOIN {$wpdb->term_relationships} ON {$wpdb->term_relationships}.term_taxonomy_id={$wpdb->term_taxonomy}.term_taxonomy_id
INNER JOIN {$wpdb->posts} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id
INNER JOIN (SELECT @rownum := NULL, @prev := 0) AS rownum_initializer ON 1=1
WHERE 1=1
AND {$wpdb->posts}.post_type='post'
AND {$wpdb->posts}.post_status='publish'
AND {$wpdb->term_taxonomy}.taxonomy='%s'
ORDER BY {$wpdb->posts}.post_parent DESC, {$wpdb->posts}.post_date DESC
) x
) categorized_posts
INNER JOIN (SELECT MAX(ID) AS post_id,post_parent FROM {$wpdb->posts} WHERE post_type='attachment' GROUP BY post_parent) attachment_join ON attachment_join.post_parent=categorized_posts.post_id
INNER JOIN {$wpdb->posts} attachments ON attachments.ID=attachment_join.post_id
WHERE
categorized_posts.rownum=1
GROUP BY
categorized_posts.term_id
ORDER BY
categorized_posts.term_name
SQL;
return $wpdb->get_results($wpdb->prepare($sql,$taxonomy));
}
noterete ho separato la logica in modo che si può ottenere la lista di tutti i termini e le loro tassonomia latests post con una foto chiamando la funzione get_taxonomy_latest_posts_with_attachment()
e passandolo un identificatore tassonomia, in questo modo:
$post_tags = get_taxonomy_latest_posts_with_attachment('post_tags');
A causa della complessità del SQL in quella funzione non ho intenzione di provare a spiegarlo (o sarei qui tutta la notte) , ma se si dispone di follow up specifiche domande, Chiedi. Ad ogni modo, ecco cosa gli sguardi codice come dalla mia parte di prova con i dati di test:
(fonte: mikeschinkel.com )
P.S. La gente nelle foto sono miei amici e tutto il lavoro con WordPress in un modo o nell'altro. Spero che non mi dispiace usare la loro somiglianza. :)
Altri suggerimenti
Questo gancio aggeggio è un pò disordinato, perché non basta chiamare home_cats()
nel modello?
Prova questo (nota che si tratta di query per categoria e può ottenere brutto per le prestazioni):
function home_cats() {
$args = array(
'orderby' => 'name',
'order' => 'ASC',
);
$categories = get_categories($args);
echo '<ul>';
foreach ( $categories as $category ) {
$link = get_category_link($category->term_id);
$title = sprintf(__("View all posts in %s"), $category->name);
$posts = get_posts( array(
'cat' => $category->term_id,
'numberposts' => 1,
) );
$post = $posts[0];
$thumbnail = get_the_post_thumbnail($post->ID);
echo "<li><a href='{$link}' title='{$title}'>{$thumbnail}{$category->name}</a></li>";
}
echo '</ul>';
}
Ci sono diversi modi alla mia per immagini, di solito vado con ottenere l'immagine .