Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Så här add to Sticky inlägg i WordPress Custom Post Type Archives

Ett sätt att hjälpa besökarna att hitta dina viktigaste posts är att placera dem högst upp på sidan där de lättast kan notice.

Men medan WordPress utvalda inlägg kan göra detta med standardinlägg, fungerar det inte för några custom post types (CPTs) som du har skapat. Enligt vår erfarenhet är det enklaste sättet att add to denna funktionalitet till din WordPress site med ett plugin.

I den här artikeln visar vi dig hur du lägger till sticky post-funktionalitet till dina anpassade posttyper och visar dem på custom post type archive pages.

How to Add Sticky Posts in WordPress Custom Post Type Archives

Varför göra WordPress Custom inlägg Sticky?

Om du skapar content för din WordPress website med ett annat format än ett vanligt post eller page, så använder du förmodligen redan en custom post type. Om du till exempel runar en website för bokrecensioner kan du ha skapat en Book Reviews post type.

Du kanske vill placera ditt viktigaste content högst upp i arkivet för custom post type. Det är ett av de bästa sätten att utvalt fördjupat och tidskänsligt content, liksom dina mest populära customize inlägg.

Men medan WordPress erbjuder en utvald inläggsfunktion, är detta inte tillgängligt för custom post types.

Låt oss ta en titt på hur du lägger till en sticky-funktion till dina custom post type archive pages.

Lägga till Sticky inlägg i Custom Post Types

Först måste du installera och aktivera pluginet Sticky Posts – Switch. För mer detaljer, se vår Step-by-Step guide om hur du installerar ett plugin för WordPress.

Note : Även om detta plugin inte har uppdaterats på ett tag fungerar det fortfarande bra i våra tester. Du kanske vill läsa vår artikel om om du vill använda tillägg som ej testats med din WordPress-version.

Vid aktivering måste du besöka Settings ” Sticky Posts – Switch page för att konfigurera plugin. Markera bara boxen bredvid de custom post types som du vill kunna göra sticky.

För denna tutorial kommer vi att kontrollera post typen ”Book Reviews”.

Visit the Settings » Sticky Posts - Switch Page to Configure the Plugin

Efter det måste du klicka på knappen ”Save Changes” längst ner på vyn.

Nu, när du besöker administratörssidan för den custom post typen, kommer du att notera en new column där du kan göra posts sticky. Allt du behöver göra är att clicka på stjärnan bredvid de inlägg du vill utvalt inlägg.

Click the Star Next to the Posts You Wish to Make Sticky

Du har nu gjort (fast)klistrat inlägget. Problemet är att WordPress bara visar (fast)klistrade inlägg på home page. Nästa inlägg handlar om hur du visar (fast)klistrade inlägg på pages i archive.

Displaying Sticky Inlägg i Custom Post Type Archives

För att visa dina sticky posts högst upp på din custom post archive page måste du skapa en new mall.

För att göra detta måste du använda en FTP-klient eller alternativet filhanterare i kontrollpanelen på ditt WordPress webbhotell. Om du inte har använt FTP tidigare kan du läsa vår guide om hur du använder FTP för att uploada filer till WordPress.

Du måste komma åt din site med hjälp av din FTP-klient eller filhanterare och sedan gå till /wp-content/themes/YOURTHEME/ folder.

Om du till exempel använder temat Twenty Twenty-One måste du navigera till /wp-content/themes/twentytwentyone/.

Därefter måste du skapa en new fil i den foldern med ett namn som gillar archive-POSTTYPE.php.

Till exempel, om din custom post type slug är ”bookreviews”, bör du skapa en new fil som heter archive-bookreviews.php.

Visit Your Theme Folder Using an FTP Client

Efter det måste du hitta filen archive.php i samma folder. Kopiera helt enkelt innehållet i archive.php och klistra in det i den nya filen som you har skapat.

Nästa steg kräver att du addar kod till dina theme-filer. Om du behöver hjälp med att lägga till kod på din site kan du läsa vår guide om hur du lägger till custom code i WordPress.

När du är klar måste du add to följande kod till ditt temas functions.php-fil eller ett code snippets plugin som WPCode (rekommenderas):

function wpb_cpt_sticky_at_top( $posts ) {
  
    // apply it on the archives only
    if ( is_main_query() && is_post_type_archive() ) {
        global $wp_query;
  
        $sticky_posts = get_option( 'sticky_posts' );
        $num_posts = count( $posts );
        $sticky_offset = 0;
  
        // Find the sticky posts
        for ($i = 0; $i < $num_posts; $i++) {
  
            // Put sticky posts at the top of the posts array
            if ( in_array( $posts[$i]->ID, $sticky_posts ) ) {
                $sticky_post = $posts[$i];
  
                // Remove sticky from current position
                array_splice( $posts, $i, 1 );
  
                // Move to front, after other stickies
                array_splice( $posts, $sticky_offset, 0, array($sticky_post) );
                $sticky_offset++;
  
                // Remove post from sticky posts array
                $offset = array_search($sticky_post->ID, $sticky_posts);
                unset( $sticky_posts[$offset] );
            }
        }
  
        // Look for more sticky posts if needed
        if ( !empty( $sticky_posts) ) {
  
            $stickies = get_posts( array(
                'post__in' => $sticky_posts,
                'post_type' => $wp_query->query_vars['post_type'],
                'post_status' => 'publish',
                'nopaging' => true
            ) );
  
            foreach ( $stickies as $sticky_post ) {
                array_splice( $posts, $sticky_offset, 0, array( $sticky_post ) );
                $sticky_offset++;
            }
        }
  
    }
  
    return $posts;
}
  
add_filter( 'the_posts', 'wpb_cpt_sticky_at_top' );
 
// Add sticky class in article title to style sticky posts differently
 
function cpt_sticky_class($classes) {
            if ( is_sticky() ) : 
            $classes[] = 'sticky';
            return $classes;
        endif; 
        return $classes;
                }
    add_filter('post_class', 'cpt_sticky_class');

Den här koden flyttar dina (fast)klistrade inlägg högst upp. Om ditt theme använder funktionen post_class(), så adderar den också en ’sticky’-klass så att du kan utforma dina (fast)klistrat inlägg med CSS.

Så här ser arkivet för den custom post typen Book Reviews ut på vår demo site. Innan koden lades till var det (fast)klistrade inlägget tvåa på listan.

Preview of Sticky Post on Custom Post Type Archive

Du kan nu styla dina (fast)klistrade inlägg genom att använda .stick y-klassen i ditt temas style .css stylesheet. Här är ett exempel:

.sticky { 
background-color:#ededed;
background-image:url('http://example.com/wp-content/uploads/featured.png');
background-repeat:no-repeat;
background-position:right top;
}

Här är en updating screenshot från vår demo website.

Preview of CSS Styling of Sticky Post

Expertguider om fast)klistrade inlägg

Nu när du vet hur du addar sticky posts till custom post type archives, kanske du gillar att se några andra guider relaterade till sticky posts i WordPress.

Vi hoppas att denna tutorial hjälpte dig att lära dig hur du lägger till (fast)klistrade inlägg i WordPress custom post type archives. You may also want to see our guide on how to speed up your WordPress website or our expert picks for the best WordPress survey plugins.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Avslöjande: Vårt innehåll stöds av våra läsare. Det innebär att om du klickar på några av våra länkar, kan vi tjäna en provision. Se hur WPBeginner finansieras, varför det är viktigt, och hur du kan stödja oss. Här är vår editoriala process.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Den ultimata WordPress-verktygslådan

Få GRATIS tillgång till vår verktygslåda - en samling WordPress-relaterade produkter och resurser som varje professionell användare bör ha!

Reader Interactions

14 kommentarerLämna ett svar

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Clare says

    I got a custom post type to be ”sticky” in an archive in 15 minutes following your example. Super helpful, thank you!

  3. rom says

    Hi,

    I’m banging my head right now….
    I’m using this plugin, it works fine, I can see it in the admin, and on the data base, I can see it update the sticky_posts in wp_options. But, when I try to use ’post__not_in’ => get_option(’sticky_posts’), it doesn’t filter any thing.
    So I try to var_dump(get_option(’sticky_posts’)), and all I get is the id of the ’normal post’, not the full list of id who I can see are in the wp_options/sticky_posts.

    Which mean if I try to use is_stiky in my loop, it only work in ’normal’ post, not in CPT, which is logic, since get_option(’sticky_posts’) is not working properly…. Any idea how I can fix that ? it’s driving me crazy :D

  4. Markus Froehlich says

    You can use this Sticky Post Switch Plugin
    It also enables the featuere for custom post types

  5. Pat Ducat says

    This works good however it makes it sticky on every page of a paginated archive. Is this how the built-in sticky functionality for standard posts work too?

  6. Aaron says

    How could i set this up to work with a custom taxonomy archive page?
    I’ve tried adding ’is_tax’ and ’is_category’ instead of the is_post_type_archive() on line 4 of your function but it just breaks the page.

    I’m missing something obviously but can’t seem to find it.
    Any ideas?

  7. Daniel Dropik says

    Thanks. Is it possible to adapt this tutorial to display sticky posts onto a specialized page template, rather than on the archives page? If so how might I accomplish this?

    • WPBeginner Support says

      if the custom taxonomy is displaying post types with sticky posts support, then you can display it in the same manner. Instead of archive-post-type.php template, make changes in taxonomy-custom-taxonomy.php template.

      Administratör

  8. Mr.Ultra says

    Thanks. This is useful.
    But if it’s possible not using a plugin to add sticky functionality to custom post types?
    Can you share the snippet?

Lämna ett svar

Tack för att du väljer att lämna en kommentar. Tänk på att alla kommentarer modereras enligt våra policy för kommentarer, och din e-postadress kommer INTE att publiceras. Vänligen använd INTE nyckelord i namnfältet. Låt oss ha en personlig och meningsfull konversation.