Action

Post to Ghost with Options

Posted by agiletortoise, Last update 10 months ago

Example action demonstrating use of the Ghost API via script to create a new post, prompting for options prior to posting.

Note: The first time this action is run, you will be prompted for the Ghost site base URL, and your staff access token, which can be copied from Ghost admin, under your account profile.

For more information on Ghost integration, see our integration guide

Steps

  • script

    // configure title and body
    // body should contain HTML, so pre-process Markdown
    const title = draft.processTemplate("[[display_title]]")
    const body = draft.processTemplate("%%[[body]]%%")
    
    let f = () => {
    	// prompt for options
    	let p = new Prompt()
    	p.title = "Ghost Options"
    	p.message = "Select options for this Ghost post."
    	
    	p.addTextField("slug", "Slug", "")
    	p.addTextView("excerpt", "Excerpt", "")
    	p.addLabel("Status", "Status")
    	p.addTextField("tags", "Tags (comma-separated)", "")
    	p.addSwitch("featured", "Featured", false)
    	p.addSegmentedControl("status", "Status", ["Draft", "Published"], "Draft")
    	p.addButton("Post")
    	
    	if (!p.show()) { return false }
    
    	// construct data to send to Ghost API
    	// see API docs for details: https://ghost.org/docs/admin-api/#creating-a-post
    	let post = {
    		"title": title,
    		"html": body,
    		"status": p.fieldValues["status"].toLowerCase(),
    		"featured": p.fieldValues["featured"]		
    	}
    	let slug = p.fieldValues["slug"]
    	if (slug.length > 0) {
    		post["slug"] = slug
    	}
    	let excerpt = p.fieldValues["excerpt"]
    	if (excerpt.length > 0) {
    		post["custom_excerpt"] = excerpt
    	}
    	let tags = p.fieldValues["tags"]
        if (tags.length > 0) {
    		post["tags"] = tags.split(",").map(t => t.trim())
    	}
    	let data = {
    		"posts": [
    			post
    		]
    	}
    
    	// make request to API
    	let g = new Ghost()
    	let response = g.request({
    		"path": "/admin/posts/",
    		"method": "POST",
    		"parameters": {"source": "html"},
          "data": data
    	})
    	if (response.success) {
    		let url = response.responseData["posts"][0]["url"]
    		if (url) {
    			console.log(`Ghost Post Created: ${url}`)
    		}
    		console.log(response.responseText)
    	}
    	else {
    		console.log(`Ghost Post Failed: ${response.statusCode}
    ${response.responseText}
    `)
    		context.fail()
    	}
    	return true
    }
    
    if (!f()) {
    	context.cancel()
    }
    
    
    

Options

  • After Success Default
    Notification Info
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.