api.addPostMenuButton with conditions

First of all, I apologize for my poor English.
I want to add “Show More…” button.
The post in the image below consists of 10 lines of text, but only 5 lines are displayed.

User can see the full text by clicking on ShowMore.

This button should be branched to give or not give a button depending on the height of the cooked part of each post or the number of lines.

I don’t know how to branch using api.addPostMenuButton, so currently even a small post with only one line like the following is given this button.

This is not very desirable to me.

I’m thinking that the conditional branch should be able to get the height of the COOKED or the number of lines (or characters).
I looked at the documentation, but I can’t find any options for api.addPostMenuButton.
Any help would be greatly appreciated.

1 Like

The api.addPostMenuButton method only cares about the value you return. That value needs to be an object. Anything you do before that return doesn’t matter. The button will get rendered for each post, and the method gives you the post object that you can use for your work.

For example, let’s say I want the button to only show up on posts that have more than 300 words. I can then do something like this.

common > header

<script type="text/discourse-plugin" version="0.8">
  const MIN_WORD_COUNT = 300;

  api.addPostMenuButton("myButton", (post) => {
    // you can log the post properties to see what you have to work with
    // console.log(post);

    // example
    const roughWordCount = post.cooked.match(/\S+/g).length;

    if (roughWordCount < MIN_WORD_COUNT) {
      // button won't render

    // button will render, create the return object 
    const result = {
      action: SOME_ACTION,
      icon: ICON_NAME,
      className: CLASSNAMES,
      position: "first", // can be `first`, `last` or `second-last-hidden`

    // add a lable if on desktop
    if (!post.mobileView) {
      result.label = LABLE_TRANSLATION_KEY;

    // retun the object
    return result;

Change the uppercase stuff to actual data and try it on a post that has more than 300 words. You’ll see that it renders there.