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 addar du custom styles till WordPress Visual Editor

Vill du add to custom styles i WordPress visual editor? Genom att lägga till customize-format kan du snabbt tillämpa formatering utan att byta till textredigeraren. I den här artikeln visar vi dig hur du addar customizes till WordPress visual editor.

Adding custom styles in WordPress visual editor

Note: Denna tutorial kräver grundläggande kunskaper om CSS.

Varför och när du behöver Custom Styles för WordPress Visual Editor

Som standard kommer WordPress visual editor med några grundläggande formaterings- och stilalternativ. Ibland kan du dock behöva egna custom styles för att add to CSS-knappar, content block, taglines, etc.

Du kan alltid byta från visual editor till textredigerare och lägga till custom HTML och CSS. Men om du regelbundet använder vissa stilar, skulle det vara bäst att lägga till dem i visual editor så att du enkelt kan återanvända dem.

This will save you time spent on switching back and forth between text and visual editor. It will also allow you to consistently use the same styles throughout your website.

Viktigast av allt är att du enkelt kan tweaka eller updating stilar utan att behöva redigera posts på din website.

Med detta sagt, låt oss ta en titt på hur du add to custom styles i WordPress visual editor.

Metod 1: Add Custom Styles i Visual Editor med hjälp av Plugin

Det första du behöver göra är att installera och aktivera TinyMCE Custom Styles plugin. För mer detaljer, se vår steg-för-steg guide om hur du installerar ett WordPress plugin.

Efter aktivering måste du besöka Settings ” TinyMCE Custom Styles page för att konfigurera plugin-inställningarna.

TinyMCE Custom Styles settings

Tillägget tillåter dig att välja location för stylesheet-filer. Det kan använda ditt tema eller barntemasstylesheets, eller så kan du välja en egen custom location.

Efter det måste du klicka på knappen ”Save All Settings” för att lagra dina ändringar.

Nu kan du add to dina custom styles. Du måste rulla ner lite till style section och klicka på knappen Add new style.

Först måste du enter en rubrik för stilen. Denna rubrik kommer att displayed i rullgardinsmenyn. Därefter måste du välja om det är ett inline-, block- eller selector-element.

Efter det lägger du till en CSS-klass och lägger sedan till dina CSS-regler som visas i screenshot under.

Adding a new custom style

När du har lagt till en CSS-stil klickar du helt enkelt på knappen ”Save All Settings” för att lagra dina ändringar.

Du kan nu edit en befintlig post eller skapa en new. Du kommer att notice en rullgardinsmeny Format i den andra row i WordPress visual editor.

Custom style menu in TinyMCE

Välj helt enkelt lite text i editorn och välj sedan din custom style från Formats dropdown-menyn för att tillämpa den.

You can now preview your post to see that your custom styles are applied correctly.

Metod 2: Lägg manuellt till Custom Styles till WordPress Visual Editor

Denna metod är obligatorisk för att du manuellt ska kunna add to kod till dina WordPress-filer. Om det här är första gången du lägger till kod i WordPress, vänligen se vår guide om hur du lägger till code snippets från webben till WordPress.

Step-by-Step: Lägg till en rullgardinsmeny för customizes i WordPress Visual Editor

Först lägger vi till en rullgardinsmeny för Formats i WordPress visual editor. Denna rullgardinsmeny kommer sedan att allow oss att välja och tillämpa våra custom styles.

Du måste add to följande kod i functions.php-filen i ditt theme eller i ett site-specifikt plugin.

function wpb_mce_buttons_2($buttons) {
	array_unshift($buttons, 'styleselect');
	return $buttons;
}
add_filter('mce_buttons_2', 'wpb_mce_buttons_2');

Step 2: Add select alternativ till rullgardinsmeny

Nu måste du add to alternativen till rullgardinsmenyn som du just har skapat. Du kommer sedan att kunna välja och tillämpa dessa alternativ från rullgardinsmenyn Formats.

I den här tutorialen lägger vi till tre custom styles för att skapa content block och knappar.

Du måste add to följande kod till ditt temas functions.php-fil eller ett site-specifikt plugin.

/*
* Callback function to filter the MCE settings
*/

function my_mce_before_init_insert_formats( $init_array ) {  

// Define the style_formats array

	$style_formats = array(  
/*
* Each array child is a format with it's own settings
* Notice that each array has title, block, classes, and wrapper arguments
* Title is the label which will be visible in Formats menu
* Block defines whether it is a span, div, selector, or inline style
* Classes allows you to define CSS classes
* Wrapper whether or not to add a new block-level element around any selected elements
*/
		array(  
			'title' => 'Content Block',  
			'block' => 'span',  
			'classes' => 'content-block',
			'wrapper' => true,
			
		),  
		array(  
			'title' => 'Blue Button',  
			'block' => 'span',  
			'classes' => 'blue-button',
			'wrapper' => true,
		),
		array(  
			'title' => 'Red Button',  
			'block' => 'span',  
			'classes' => 'red-button',
			'wrapper' => true,
		),
	);  
	// Insert the array, JSON ENCODED, into 'style_formats'
	$init_array['style_formats'] = json_encode( $style_formats );  
	
	return $init_array;  
  
} 
// Attach callback to 'tiny_mce_before_init' 
add_filter( 'tiny_mce_before_init', 'my_mce_before_init_insert_formats' ); 

Du kan nu lägga till ett nytt post i WordPress och klicka på rullgardinsmenyn Formats i Visual editor. You will notice that your custom styles are now visible under formats.

Om du väljer dem gör det dock ingen skillnad i postens editor just nu.

Step-by-Step 3: Add CSS Styles

Nu är det sista steget att lägga till CSS-stilregler för dina customizes.

You will need to add this CSS into your theme or child theme’s style.css and editor-style.css files.

.content-block { 
    border:1px solid #eee; 
    padding:3px;
    background:#ccc;
    max-width:250px;
    float:right; 
    text-align:center;
}
.content-block:after { 
    clear:both;
} 
.blue-button { 
	background-color:#33bdef;
	-moz-border-radius:6px;
	-webkit-border-radius:6px;
	border-radius:6px;
	border:1px solid #057fd0;
	display:inline-block;
	cursor:pointer;
	color:#ffffff;
	padding:6px 24px;
	text-decoration:none;
}

.red-button {
	background-color:#bc3315;
	-moz-border-radius:6px;
	-webkit-border-radius:6px;
	border-radius:6px;
	border:1px solid #942911;
	display:inline-block;
	cursor:pointer;
	color:#ffffff;
	padding:6px 24px;
	text-decoration:none;
}

Custom styles in WordPress post editor

Editor stylesheet kontrollerar utseendet på ditt content i visual editor. Kontrollera ditt temas dokumentation för att ta reda på platsen för den här filen.

Om ditt theme inte har en editor stylesheet-fil kan du alltid skapa en. Skapa helt enkelt en new CSS-fil och namnge den custom-editor-style.css.

Du måste uploada den här filen till ditt temas root directory och sedan add to den här koden i ditt temas functions.php-fil.

function my_theme_add_editor_styles() {
    add_editor_style( 'custom-editor-style.css' );
}
add_action( 'init', 'my_theme_add_editor_styles' );

Det är all. Du har utan problem add to dina custom styles i WordPress visual editor. Lek gärna med koden genom att lägga till dina egna element och stilar.

Vi hoppas att den här artikeln hjälpte dig att lära dig hur du lägger till anpassade stilar i WordPress visual editor. Du kanske också vill se vår guide om hur du lägger till anpassade stilar till WordPress widgets.

Om du gillade den här artikeln, vänligen prenumerera på vår YouTube-kanal för WordPress video tutorials. Du kan också hitta oss på Twitter och 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

50 kommentarerLämna ett svar

  1. Syed Balkhi

    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. Toufic Ahemmed

    This guys are awesome. they help me most of the time. thank you very very much.

    • WPBeginner Support

      Glad we could help :)

      Administratör

  3. Aslan French

    This article should be updated with Gutenberg in mind, as this kind of functionality has been added to the Rich Text API recently.

    • WPBeginner Support

      Hi Aslan,

      Thanks for the suggestion. We will definitely look into older articles once Gutenberg is out.

      Administratör

  4. Mehrdad

    Thanks a lot.
    This article really helped me.

  5. sabbi

    This adds classes to a p-tag doesnt it?
    Is there a way to even create own tags?
    Or another thing:will a chosen custom Format overwrite a previously chosen h-tag with a p? Would be necessary to prevent a client from getting in trouble when hes clicking around in the default AND custom styles.

  6. Britany

    Unfortunately this didn’t help me at all. Is there an article that explains what each of the fields you have to fill in mean?

    All I need is a way to apply the same formatting to quotes on my podcast show notes pages. Each quote is the the same font (that I have set-up as a headline style), bolded, and centered.

    I get tired of manually applying each part of the format to every quote and just a way to click one button and be done.

  7. Syams

    Please, tell me how to add a new font to WP visual editor.

  8. Moya Nicholson

    Thank you. Really helpful.

  9. stanley

    I need to modify my theme WP

    hell me please

  10. Sandy Connolly

    THANK YOU FOR THIS!!! OMG!!!! How helpful upon handing a site over to a client who wants to be able to add his/her own content based on our design!

  11. Marcin

    Hi, I develop WordPresses every day and do everything with WP but this piece of code is one of the most useful I’ve seen for long time… It is exactly what default WYSIWYG is (now I can say: was) missing! It allows to do some stunnig things inside content field. Thank You for sharing!

  12. Foxglove

    I have been using this plugin for a while now, but it is no longer available from wordpress.org — apparently no longer updated or supported. Is anyone aware of any alternatives other than the manual method you describe?

    • Lisa McMahon

      Here’s an updated/forked version of the original plugin mentioned in the article: TinyMCE Custom Styles

      • WPBeginner Support

        Hey Lisa, thanks for pointing this out. We have updated the article with the updated/forked version.

        Administratör

  13. Shubha Das

    I want to add p instead of span. But when I change block name span to p, it doesn’t work.

    ’title’ => ’Note’,
    ’block’ => ’p’,
    ’classes’ => ’note’,
    ’wrapper’ => true,

  14. MacKenzie

    I found this really helpful and I feel like I almost have it but it isn’t quite working yet. My text gets properly tagged with the span and class tags in the editor when selected – but none of the styles I put in the style sheet are being applied to the published note.

  15. Frank

    I always become nervous and feel like vomiting if some customer needs wordpress tweaks. Coll, this style pulldown BUT, as someone said before, completely useless if styles cannot be withdrawn afterwards and only add up, add up, add up…

    I’m used to these half baked sulotions in wordpress – normally there’s also a complementary half-baked solutions to half repair the first one. But here?

    Now HOW would you suggest TO REMOVE CUSTOM STYLES added via the styles pulldown. Code view is in no way acceptable for my client?

    I’d be unbelievably lucky if someone has found a way to do that and would share this knowledge (and for putting the catastrophe called wordpress out of my reach for( i hope) a very long time).

    Thanks a lot in advance!

    Frank

    • Chris

      Click on the style in the pulldown again. Done.

  16. Shafi ken

    Thanks for the helpful tutorial. Thanks

  17. K Shazzad

    Whole tutorial worked flawlessly for me. Thanks a bunch ;)

  18. Stef

    I tried out this plugin but realized, that when you change a custom style, It won’t update those you inserted already. You have to go back and reinsert them, because the feature adds the style inline and not via stylesheet

  19. Phil

    Thanks for the helpful tutorial. Is there any performance penalty in using the plugin rather than hand-coding it? Thanks,

    • WPBeginner Support

      No, but for reusing elements this method is quite handy. It is also useful, if you are building a site for a client and want them to be able to add things from the visual editor.

      Administratör

  20. Sei

    Thanks for the tutorial!
    Is there a way to add two markups at once? Like, getting something like text

    • Sei

      Okay, your comments converts HTML. I mean, I’d like to get both ’h1’ and ’span’ markups around my text by clicking on only one style.

  21. Lily

    I’ve managed to do the custom classes and the elements do show with the right classes in the text editor and on the page, but the class isn’t applied in the visual editor which makes it very unclear whether it’s worked or not for the user. Is there any way to fix that?

  22. Bonnie Dasher-Andersen

    I’ve added two custom styles. When I go to edit a page, I have two Format menus, each one with the same entries (the two styles that I created). When I try to apply these styles, nothing happens. I can see the tag in the Text view, but when I view the page – the style hasn’t been applied.

    Any suggestions? Need to figure this out for a client who will be updated this WP site and is not very savvy.

    • Marcello

      I had the same problem, where the tags weren’t applied to code. Fixed it by setting ’wrapper’ to ’false’. I don’t know the technical reasons, just tested and it worked. Hope it helps!

      • hugotom

        I had the same problem that the style sheet is not recorded.
        Solution
        If you already have this recording style sheets in the functions.php file should add right there stylesheet custom-editor-style.css

        Example:

        function styles_theme(){
        wp_enqueue_style(’bootstrap_css’, get_template_directory_uri() . ’/sources/bootstrap/bootstrap.min.css’);
        wp_enqueue_style(’main_css’, get_template_directory_uri() . ’/style.css’);
        wp_enqueue_style(’theme_css’, get_template_directory_uri() . ’/custom/css/theme.css’);
        wp_enqueue_style(’editor_css’, get_template_directory_uri() . ’/custom-editor-style.css’); // HERE
        };

  23. Raphael Landau

    I’ve used this and also had the issue where the style/class is implemented to the entire Paragraph. This is because you set the style format as ”block”. (’block’ => ’span’,).

    Quickly visiting the official Wordpress codex, discovers much more options for style formatting.

    http://codex.wordpress.org/TinyMCE_Custom_Styles

    Since span is an inline style be default, you should replace ’block’ with ’inline’, and viola! You’re styling should work as expected.

    so in short:

    array(
    ’title’ => ’Your Title’,
    ’inline’ => ’span’,
    ’classes’ => ’your-class’,
    ’wrapper’ => true,
    ),

  24. nemaha

    Hi,
    great tutorial, thanks for that! I, too, have the problem, that style (a span) is applied to the whole paragraph. What I intend to do: Write a headline and format it as heading 1, then mark only one specific word within that headline to add a custom style. Any update on how to fix this? Thanks!

  25. bekee

    i, too, have the problem where it applies the style to the whole paragraph, not just the selected element. any update on this? thanks!

  26. Debbie

    Having the same issue. Highlight one word, but takes effect on entire paragraph.

  27. James

    I find a couple of problems. It does seem to work, but not as expected. Will not do for someone who does not know code.

    1. Highlight a single word in a paragraph to add a but the is added to the entire paragraph, not just the highlighted word.
    2. No way to remove the css without editing code. My client does not do code! Even tried to make a class of .nothing but the new class is only added to any others, does not replace existing class.

  28. Sheikh Zuhaib Siddiqui

    Hey I have an error in add media. When I try to upload any media, there is only continue loading and not showing up any media and can upload media……………Let me know what the mistake here???

    But this is working fine …………just error in media uploader. please provide me this solution.

  29. Marlice

    Hi. Thank you for this great tutorial. I have a problem with content that is already in the editor. If I mark a word or a part of text and choose a style (for example ”blue button” – from your code) it wraps not only the marked word or part of text. Instead it marks the whole content and put a span with the class .blue button on it. I tried it several times with other pages and posts – always the same: if the content was already there and I marked it, then the whole content get the span class. This does not happen if I wrap a new edited text in the page/post – than everything works fine. Does anybody has this phenomen too?
    Thank you,
    Ute

  30. John-Henry Ross

    Hi. I tried this method and it works like a charm, exactly what I was looking for, thank you. I just want to find out if there is a way to add styles to a subfolder instead of just adding it under a format button. E.g. add a headings subfolder with all heading stylings, add div submenu with div stylings, etc.

  31. dave

    Thanks!
    It’s great to show 2 methods, too… my clients cower in fear at handling any code.

    I will sometimes use custom fields to ”force” safe additional styles, but the TinyMCE can be handled by some people, so I’ll kee that in mind. :)

    Ciao, Dave

  32. WPBeginner Staff

    you do not need to add the dot in

    classes’ => ’.alert-blue’,

    It should be

    classes’ => ’alert-blue’,

    • Jeff Gaudette

      Sadly, this didn’t work. I removed the period, but still nothing applies in the editor. I know you’re not a help desk, but here’s a screenshot if you’re interested: http://screencast.com/t/JI0zMvcH

      Thanks for all the great stuff you put out!

      • WPBeginner Staff

        Can you paste the code you added in your functions.php file. Also paste the CSS you are using for these buttons.

        • Jeff Gaudette

          Sure. Functions:

          /*
          * Callback function to filter the MCE settings
          */

          function my_mce_before_init_insert_formats( $init_array ) {

          // Define the style_formats array

          $style_formats = array(
          // Each array child is a format with it’s own settings
          array(
          ’title’ => ’Alert’,
          ’block’ => ’span’,
          ’classes’ => ’entry p.alert-blue’,
          ’wrapper’ => true,

          ),
          array(
          ’title’ => ’Alert Blue’,
          ’block’ => ’p’,
          ’classes’ => ’alert-blue’,
          ’wrapper’ => true,
          ),
          array(
          ’title’ => ’Blue Button’,
          ’block’ => ’span’,
          ’classes’ => ’alert-blue-button’,
          ’wrapper’ => true,
          ),
          );
          // Insert the array, JSON ENCODED, into ’style_formats’
          $init_array[’style_formats’] = json_encode( $style_formats );

          return $init_array;

          }
          // Attach callback to ’tiny_mce_before_init’
          add_filter( ’tiny_mce_before_init’, ’my_mce_before_init_insert_formats’ );

          CSS

          .alert-blue{
          background: none repeat scroll 0 0 #E7F4FD;
          border: 1px solid #C5D7E3;
          color: #3A5971;
          font-size: 18px;
          line-height: 24px;
          text-align: center;
          margin: 0 0 15px !important;
          padding: 15px 25px;
          width: auto;
          }

  33. WPBeginner Staff

    Did you add the CSS in your stylesheet?

    Make sure that the style rules you add in your CSS match the classes you add in the Callback function to filter the MCE settings.

  34. Kemi O

    TinyMCE Advanced Professsional Formats and Styles is only supported up to WP version 3.6.1

  35. Keely Worth

    I avoid the Visual Editor like the plague! Only use it if I have to switch to it to use a theme’s built-in shortcode button. Otherwise – never use it.

  36. Blair2004

    I have tried first method, new style are available but, while i’m selecting one, nothing happens…

  37. Jeff Gaudette

    I am trying to do this with a block and having no luck. Code is:

    array(
    ’title’ => ’Alert Blue’,
    ’block’ => ’p’,
    ’classes’ => ’.alert-blue’,
    ’wrapper’ => true,
    ),

    It works when I use span, but this necessitates a span class, which I can’t use.

    When i use the above code, nothing happens in the wp editor. I select the text, click the Alert Blue formatting option and nothing happens: http://screencast.com/t/dijujZ2ZdqBy

    Any advice?

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.