简体   繁体   English

如何使用python XML-RPC API更改/删除wordpress帖子中的标签

[英]How to change/delete tags in wordpress post with python XML-RPC API

Some wordpress themes use tags (for example 'featured') to show featured content on front page. 某些wordpress主题使用标签(例如“精选”)在首页上显示精选内容。

I have a python script that tags all posts with 'featured' tag, if certain custom_field value in a post is above defined value. 我有一个python脚本,如果某个帖子中的某些custom_field值高于定义的值,则会使用“功能”标签标记所有帖子。 That script also reduces these values each time it runs. 该脚本每次运行时也会减少这些值。 Now, I would like to delete 'featured' tag from a post if this custom_field is below defined value. 现在,如果此custom_field低于定义的值,我想从帖子中删除“功能”标签。

to add tags for existing post I use: 为我使用的现有帖子添加标签:

server = xmlrpclib.ServerProxy(wp_url)
client = Client(wp_url, wp_username, wp_password)

post = client.call(posts.GetPost(postID))  
post.custom_fields = [{'id': featuredscoreID, 'key':'featuredscore','value': featscore}]
post.terms_names = {
    'post_tag': ['new tag'],
    }
post.call(posts.EditPost(postID, fpost))

but this code will only append tags. 但是此代码只会附加标签。

print post.terms 

will give me something like this: 会给我这样的东西:

[<WordPressTerm: Architecture>, <WordPressTerm: featured>, <WordPressTerm: Image>, <WordPressTerm: redevelopment>, <WordPressTerm: station>]

but I have found no way to replace or delete tags from existing post wordpress with python 但是我发现没有办法用python从现有的post wordpress中替换或删除标签

something like: remove_tag(postID, 'tag') 类似于:remove_tag(postID,'tag')

thanks 谢谢

EDIT: 编辑:

It seems that it is not possible to delete tags(or tag) from post defined by post id ID using python XML-RPC API. 似乎无法使用python XML-RPC API从由帖子ID ID定义的帖子中删除标签(或标签)。 It should be possible using database queries ( Wordpress - Delete all tags by Post ID ) but this certain example did not work (for me) and if there is need to run this (script) from some other location than localhost, one would need to loosen MySQL security and open some ports. 应该可以使用数据库查询( Wordpress-通过Post ID删除所有标签 ),但是该特定示例对我而言不起作用,并且如果需要从本地主机以外的其他位置运行此(脚本),则需要放松MySQL安全性并打开一些端口。

So, as solution, delete tag from wordpress and then apply it back to posts where it should be. 因此,作为解决方案,请从wordpress中删除标签,然后将其应用到应有的位置。 To remove tags: 删除标签:

postTags = client.call(taxonomies.GetTerms('post_tag'))   

for tag in postTags:
    try:  
        if str(tag) == 'tag you would like to delete':
            client.call(taxonomies.DeleteTerm('post_tag', tag.id))         
    except:
        print "error"

automatic "featured" posts: http://imageoftheday.org/ 自动的“精选”帖子: http : //imageoftheday.org/

If you are able to add code / plugins to your wordpress instance, then you can use custom XML-RPC methods to handle this. 如果您能够在您的wordpress实例中添加代码/插件,则可以使用自定义XML-RPC方法来处理。

In Wordpress, you'll need to add a function that handles the magic on the server side. 在Wordpress中,您需要添加一个在服务器端处理魔术的函数。 (I've added this to functions.php but better WP developers may know a better place for it. Perhaps a plugin.) (我已经将其添加到functions.php但是更好的WP开发人员可能知道更好的地方。也许是插件。)

I believe you need wp_remove_object_terms for your question, but of course your custom xml-rpc function can do whatever you like. 我相信您的问题需要wp_remove_object_terms ,但是您的自定义xml-rpc函数当然可以做您想做的任何事情。 I used this approach to delete custom fields, and to interact with another plugin I have installed. 我使用了这种方法来删除自定义字段,并与已安装的另一个插件进行交互。

function xmlrpc_add_method_delete_tags( $methods ) {
  $methods['my_namespace.delete_tags'] = 'xmlrpc_delete_tags_handler';
  return $methods;
}
add_filter('xmlrpc_methods', 'xmlrpc_add_method_delete_tags');

function xmlrpc_delete_tags_handler( $args ) {
  $result = array("ok" => false);

  try {
    // inspect $args for your parameters. I like to validate with regex,
    // but they should just be at the end of $args
    $n = count($args);
    $postId   = $args[$n-3];
    $term     = $args[$n-2];
    $taxonomy = $args[$n-1];

    $del = wp_remove_object_terms( $postId, $term, $taxonomy );
    $result["ok"] = ($del === true);

    if(is_wp_error($del)) {
      $result['wp_errors'] = $del->get_error_messages();
    }
  }
  catch(Exception $ex) {
    $result["msg"] = $ex->getMessage();
  }

  return json_encode($result); // send a json response
}

In Python, define a wordpress_xmlrpc.AuthenticatedMethod (or AnonymousMethod if you don't need authentication). 在Python中,定义一个wordpress_xmlrpc.AuthenticatedMethod (如果不需要身份验证,则定义为AnonymousMethod)。

import json
from wordpress_xmlrpc import Client, AuthenticatedMethod

client = Client(WP_XMLRPC_URL, WP_USER, WP_PASSWORD)

class WordpressRemoveTag(AuthenticatedMethod):
    # method_name must match the key string you added to $methods in WP
    method_name = 'my_namespace.delete_tags'
    method_args = ('postId', 'term', 'taxonomy')

def remove_tag_from_obj(obj_id, term, tax='post_tag'):
    # return parsed json server response
    res = client.call(WordpressRemoveTag(obj_id, term, tax))
    return json.loads(res)

Then call remove_tag_from_obj(...) in python and you should get a json response from the server: 然后在python中调用remove_tag_from_obj(...) ,您应该从服务器获得json响应:

print remove_tag_from_obj(post.id, 'my_tag')
>> {"ok":true}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM