api.addPostMenuButton with conditions

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
      return;
    }

    // button will render, create the return object 
    const result = {
      action: SOME_ACTION,
      icon: ICON_NAME,
      title: TITLE_TRANSLATION_KEY,
      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;
  });
</script>

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.