How to programmatically retrieve the external_id for a topic

I’d never noticed that before. I was looking for something similar a few years ago for associating WordPress post ids with Discourse topics.

The topic’s external_id will only be returned as a property on the client if the topic has an external_id, so if the topic doesn’t have one, you won’t get a null value. This is working for me for topics that do have an external_id:

<script type="text/discourse-plugin" version="0.11.0">
api.onPageChange (() => {
    const c = api.container.lookup("controller:topic");
    if (c) {
        const m = c.get("model");
        if (m && m.hasOwnProperty('external_id')) {
        console.log("the external_id is ", m.external_id);
        }
    }
});
</script>