-
Notifications
You must be signed in to change notification settings - Fork 1
feat: CPT content seeding (Tier-1 dynamic content) #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
730f025
feat(api-pro): create_post supports CPT + taxonomy terms; importable …
BenKalsky faf8b29
refactor(api-pro): make upload_media importable (__main__ guard)
BenKalsky f4084bf
feat(api-pro): add describe_cpt.py schema discovery
BenKalsky 2e40a3c
feat(api-pro): add seed_content.py batch CPT seeder (dry-run default)
BenKalsky 0c99048
ci(api-pro): run CPT-seeding unit tests + dry-run smoke
BenKalsky a560c4c
docs(api-pro): document CPT seeding; bump to 3.6.0
BenKalsky File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| [ | ||
| { | ||
| "post_type": "projects", | ||
| "title": "Acme Rebrand", | ||
| "content": "<p>Full brand refresh.</p>", | ||
| "status": "draft", | ||
| "terms": { "project_category": ["Branding"] }, | ||
| "featured_image": 42, | ||
| "acf": { "client": "Acme", "year": 2025 }, | ||
| "jet": { "duration_weeks": 6 } | ||
| }, | ||
| { | ||
| "post_type": "projects", | ||
| "title": "Globex Site", | ||
| "content": "<p>Marketing site.</p>", | ||
| "status": "draft", | ||
| "terms": { "project_category": ["Web"] }, | ||
| "featured_image": "https://example.com/globex.jpg", | ||
| "acf": { "client": "Globex", "year": 2024 } | ||
| } | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import json, os, sys, unittest | ||
| from unittest import mock | ||
|
|
||
| SCRIPTS = os.path.join(os.path.dirname(__file__), "..", "wordpress-api-pro", "scripts") | ||
| sys.path.insert(0, os.path.abspath(SCRIPTS)) | ||
|
|
||
| import create_post # noqa: E402 | ||
|
|
||
|
|
||
| class FakeResp: | ||
| def __init__(self, payload, code=200): | ||
| self._b = json.dumps(payload).encode() | ||
| self.status = code | ||
| def read(self): return self._b | ||
| def __enter__(self): return self | ||
| def __exit__(self, *a): return False | ||
|
|
||
|
|
||
| class ResolveRestBaseTest(unittest.TestCase): | ||
| def test_uses_rest_base_from_types(self): | ||
| with mock.patch.object(create_post.urllib.request, "urlopen", | ||
| return_value=FakeResp({"rest_base": "projects"})): | ||
| self.assertEqual( | ||
| create_post.resolve_rest_base("http://x", "a", "projects"), "projects") | ||
|
|
||
| def test_falls_back_to_slug_on_error(self): | ||
| with mock.patch.object(create_post.urllib.request, "urlopen", | ||
| side_effect=Exception("404")): | ||
| self.assertEqual( | ||
| create_post.resolve_rest_base("http://x", "a", "team"), "team") | ||
|
|
||
|
|
||
| class ResolveTermsTest(unittest.TestCase): | ||
| def test_existing_term_resolves_to_id(self): | ||
| responses = [ | ||
| FakeResp({"rest_base": "project_category"}), # taxonomy rest base | ||
| FakeResp([{"id": 5, "name": "Branding"}]), # term search hit | ||
| ] | ||
| with mock.patch.object(create_post.urllib.request, "urlopen", | ||
| side_effect=responses): | ||
| out = create_post.resolve_terms("http://x", "a", | ||
| {"project_category": ["Branding"]}, | ||
| create_missing=False) | ||
| self.assertEqual(out, {"project_category": [5]}) | ||
|
|
||
|
|
||
| import seed_content # noqa: E402 | ||
|
|
||
|
|
||
| class SeedDryRunTest(unittest.TestCase): | ||
| def test_dry_run_plans_every_entry_without_network(self): | ||
| fixture = os.path.join(os.path.dirname(__file__), "fixtures", "seed.json") | ||
| with open(fixture) as f: | ||
| dataset = json.load(f) | ||
| plan = seed_content.plan_seed(dataset) | ||
| self.assertEqual(len(plan), 2) | ||
| self.assertEqual(plan[0]["post_type"], "projects") | ||
| self.assertIn("acf", plan[0]["will_set"]) | ||
| self.assertIn("terms", plan[0]["will_set"]) | ||
| self.assertEqual(plan[1]["featured_image_kind"], "url") | ||
| self.assertEqual(plan[0]["featured_image_kind"], "media_id") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,42 +1,108 @@ | ||
| #!/usr/bin/env python3 | ||
| """Create WordPress post via REST API""" | ||
| import argparse, json, os, sys, urllib.request | ||
| """Create a WordPress post or CPT entry via REST API (with taxonomy support).""" | ||
| import argparse, json, os, sys, urllib.request, urllib.parse | ||
| from base64 import b64encode | ||
|
|
||
| def create_post(url, username, password, title, content, status='draft', **kwargs): | ||
| api_url = f"{url.rstrip('/')}/wp-json/wp/v2/posts" | ||
| credentials = f"{username}:{password}".encode('utf-8') | ||
| auth_header = b64encode(credentials).decode('ascii') | ||
|
|
||
|
|
||
| def _auth(username, password): | ||
| return 'Basic ' + b64encode(f"{username}:{password}".encode()).decode() | ||
|
|
||
|
|
||
| def _get(url, auth): | ||
| req = urllib.request.Request(url, method='GET') | ||
| req.add_header('Authorization', auth) | ||
| with urllib.request.urlopen(req) as r: | ||
| return json.loads(r.read().decode()) | ||
|
|
||
|
|
||
| def _post(url, auth, payload): | ||
| req = urllib.request.Request(url, data=json.dumps(payload).encode(), method='POST') | ||
| req.add_header('Authorization', auth) | ||
| req.add_header('Content-Type', 'application/json') | ||
| with urllib.request.urlopen(req) as r: | ||
| return json.loads(r.read().decode()) | ||
|
|
||
|
|
||
| def resolve_rest_base(base_url, auth, post_type): | ||
| """Resolve a post type's REST base; fall back to the slug on any error.""" | ||
| try: | ||
| info = _get(f"{base_url.rstrip('/')}/wp-json/wp/v2/types/{post_type}", auth) | ||
| return info.get('rest_base') or post_type | ||
| except Exception: | ||
| return post_type | ||
|
|
||
|
|
||
| def resolve_terms(base_url, auth, terms_dict, create_missing=True): | ||
| """Map {taxonomy: [name|id, ...]} -> {taxonomy: [id, ...]}. | ||
|
|
||
| Names are resolved (and optionally created) via the taxonomy's REST base. | ||
| Integer-like values pass through as ids. | ||
| """ | ||
| base_url = base_url.rstrip('/') | ||
| out = {} | ||
| for taxonomy, values in (terms_dict or {}).items(): | ||
| tax_base = resolve_rest_base(base_url, auth, taxonomy) # taxonomy rest_base | ||
| ids = [] | ||
| for v in values: | ||
| if isinstance(v, int) or (isinstance(v, str) and v.isdigit()): | ||
| ids.append(int(v)); continue | ||
| q = urllib.parse.quote(str(v)) | ||
| hits = _get(f"{base_url}/wp-json/wp/v2/{tax_base}?search={q}", auth) | ||
| match = next((t for t in hits if str(t.get('name', '')).lower() == str(v).lower()), None) | ||
| if match: | ||
| ids.append(match['id']) | ||
| elif create_missing: | ||
| created = _post(f"{base_url}/wp-json/wp/v2/{tax_base}", auth, {'name': v}) | ||
| ids.append(created['id']) | ||
| else: | ||
| raise ValueError(f"Term '{v}' not found in '{taxonomy}'") | ||
| out[taxonomy] = ids | ||
| return out | ||
|
|
||
|
|
||
| def create_post(url, username, password, title, content, status='draft', | ||
| post_type='post', featured_media=None, terms=None): | ||
| """Create a post/CPT entry. Returns the created object dict. Raises on error.""" | ||
| auth = _auth(username, password) | ||
| base = url.rstrip('/') | ||
| rest_base = resolve_rest_base(base, auth, post_type) | ||
|
|
||
| data = {'title': title, 'content': content, 'status': status} | ||
| if 'featured_media' in kwargs and kwargs['featured_media']: | ||
| data['featured_media'] = int(kwargs['featured_media']) | ||
|
|
||
| request = urllib.request.Request(api_url, data=json.dumps(data).encode('utf-8'), method='POST') | ||
| request.add_header('Authorization', f'Basic {auth_header}') | ||
| request.add_header('Content-Type', 'application/json') | ||
|
|
||
| if featured_media: | ||
| data['featured_media'] = int(featured_media) | ||
| if terms: | ||
| resolved = resolve_terms(base, auth, terms) | ||
| for taxonomy, ids in resolved.items(): | ||
| data[taxonomy] = ids # REST accepts the taxonomy key with term ids | ||
|
|
||
| return _post(f"{base}/wp-json/wp/v2/{rest_base}", auth, data) | ||
|
|
||
|
|
||
| def main(): | ||
| p = argparse.ArgumentParser(description='Create WordPress post or CPT entry') | ||
| p.add_argument('--url', default=os.getenv('WP_URL') or os.getenv('WP_SITE_URL')) | ||
| p.add_argument('--username', default=os.getenv('WP_USERNAME') or os.getenv('WP_USER')) | ||
| p.add_argument('--app-password', default=os.getenv('WP_APP_PASSWORD')) | ||
| p.add_argument('--title', required=True) | ||
| p.add_argument('--content', required=True) | ||
| p.add_argument('--status', default='draft', choices=['publish', 'draft', 'pending']) | ||
| p.add_argument('--post-type', default='post') | ||
| p.add_argument('--featured-media', type=int) | ||
| p.add_argument('--terms', help='JSON {"taxonomy": ["Name or id", ...]}') | ||
| a = p.parse_args() | ||
| if not all([a.url, a.username, a.app_password]): | ||
| print(json.dumps({"error": "Missing required credentials"}), file=sys.stderr) | ||
| sys.exit(1) | ||
| try: | ||
| with urllib.request.urlopen(request) as response: | ||
| result = json.loads(response.read().decode('utf-8')) | ||
| print(json.dumps(result, indent=2)) | ||
| return result | ||
| result = create_post(a.url, a.username, a.app_password, a.title, a.content, | ||
| a.status, post_type=a.post_type, | ||
| featured_media=a.featured_media, | ||
| terms=json.loads(a.terms) if a.terms else None) | ||
| print(json.dumps(result, indent=2)) | ||
| except Exception as e: | ||
| print(json.dumps({"error": str(e)}), file=sys.stderr) | ||
| sys.exit(1) | ||
|
|
||
| parser = argparse.ArgumentParser(description='Create WordPress post') | ||
| parser.add_argument('--url', default=os.getenv('WP_URL')) | ||
| parser.add_argument('--username', default=os.getenv('WP_USERNAME')) | ||
| parser.add_argument('--app-password', default=os.getenv('WP_APP_PASSWORD')) | ||
| parser.add_argument('--title', required=True) | ||
| parser.add_argument('--content', required=True) | ||
| parser.add_argument('--status', default='draft', choices=['publish', 'draft', 'pending']) | ||
| parser.add_argument('--featured-media', type=int) | ||
|
|
||
| args = parser.parse_args() | ||
| if not all([args.url, args.username, args.app_password]): | ||
| print(json.dumps({"error": "Missing required credentials"}), file=sys.stderr) | ||
| sys.exit(1) | ||
|
|
||
| create_post(args.url, args.username, args.app_password, args.title, args.content, args.status, featured_media=args.featured_media) | ||
|
|
||
| if __name__ == '__main__': | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| #!/usr/bin/env python3 | ||
| """Describe a custom post type: rest_base, taxonomies, and discovered field keys. | ||
|
|
||
| Read-only. Samples the newest existing entry to surface ACF/meta keys so a caller | ||
| knows what to populate when seeding. | ||
|
|
||
| Usage: | ||
| python3 describe_cpt.py --post-type projects | ||
| Env: WP_URL/WP_SITE_URL, WP_USERNAME/WP_USER, WP_APP_PASSWORD | ||
| """ | ||
| import argparse, json, os, sys, urllib.request | ||
| from base64 import b64encode | ||
|
|
||
|
|
||
| def _auth(u, p): return 'Basic ' + b64encode(f"{u}:{p}".encode()).decode() | ||
|
|
||
|
|
||
| def _get(url, auth): | ||
| req = urllib.request.Request(url, method='GET') | ||
| req.add_header('Authorization', auth) | ||
| with urllib.request.urlopen(req) as r: | ||
| return json.loads(r.read().decode()) | ||
|
|
||
|
|
||
| def describe_cpt(base_url, username, password, post_type): | ||
| auth = _auth(username, password) | ||
| base = base_url.rstrip('/') | ||
| info = _get(f"{base}/wp-json/wp/v2/types/{post_type}", auth) | ||
| rest_base = info.get('rest_base') or post_type | ||
| taxonomies = info.get('taxonomies', []) | ||
|
|
||
| field_keys, sampled_id = [], None | ||
| try: | ||
| entries = _get(f"{base}/wp-json/wp/v2/{rest_base}?per_page=1&orderby=date", auth) | ||
| if entries: | ||
| sampled_id = entries[0].get('id') | ||
| meta = entries[0].get('meta', {}) or {} | ||
| acf = entries[0].get('acf', {}) or {} | ||
| keys = set(k for k in meta if not k.startswith('_')) | set(acf.keys()) | ||
| field_keys = sorted(keys) | ||
| except Exception: | ||
| pass | ||
|
|
||
| return { | ||
| 'post_type': post_type, 'rest_base': rest_base, | ||
| 'taxonomies': taxonomies, 'field_keys': field_keys, | ||
| 'sampled_entry_id': sampled_id, | ||
| 'note': '' if field_keys else 'No entries to sample; supply field keys manually.', | ||
| } | ||
|
|
||
|
|
||
| def main(): | ||
| p = argparse.ArgumentParser(description='Describe a CPT for seeding') | ||
| p.add_argument('--url', default=os.getenv('WP_URL') or os.getenv('WP_SITE_URL')) | ||
| p.add_argument('--username', default=os.getenv('WP_USERNAME') or os.getenv('WP_USER')) | ||
| p.add_argument('--app-password', default=os.getenv('WP_APP_PASSWORD')) | ||
| p.add_argument('--post-type', required=True) | ||
| a = p.parse_args() | ||
| if not all([a.url, a.username, a.app_password]): | ||
| print(json.dumps({"error": "Missing required credentials"}), file=sys.stderr); sys.exit(1) | ||
| try: | ||
| print(json.dumps(describe_cpt(a.url, a.username, a.app_password, a.post_type), indent=2)) | ||
| except Exception as e: | ||
| print(json.dumps({"error": str(e)}), file=sys.stderr); sys.exit(1) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| main() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a taxonomy has a custom
rest_base, this uses the post-type resolver, which requests/wp/v2/types/{taxonomy}rather than the taxonomy descriptor endpoint. That request fails and falls back to the taxonomy slug, so term search/creation later targets/wp/v2/{taxonomy}and breaks for taxonomies whose REST collection is renamed (the same scenario this rest_base lookup is meant to handle).Useful? React with 👍 / 👎.