我想在不使用任何插件的情况下自动在Facebook上发布我的WP博客的所有文章。
我写了一些代码来做这件事,没关系.但是,只有在发布新文章时(而不是针对修订或自动保存),我才需要调用此代码。
这是您需要看到的function.php文件的一部分:
add_action( 'save_post', 'koolmind_facebook_post_article',3 );
function koolmind_facebook_post_article( $post_id ) {
/* configuration of facebook params */
....
....
/* end config */
if ( !wp_is_post_revision( $post_id ) && !wp_is_post_autosave( $post_id ) ) {
/* retrieve some data to publish */
/* invoke my code to publish on facebook */
}
}只要单击“添加新文章”,就会调用我的代码,并将空草稿发送到我的Facebook页面。在add中,一旦我在文章正文中插入一个字符,就会触发autosave,并再次将一个新的帖子(几乎为空)发送到facebook。
我只想阻止这种自动发布,只有当我按下“发布”按钮时,我才会将我的数据发送到facebook。
这有可能吗?
更新
我终于找到了问题所在。我的fb代码里有个错误。现在的问题是,在更新我的帖子时,要避免多次公开。
下面是代码:
add_action('pending_to_publish', 'koolmind_facebook_post_article');
add_action('draft_to_publish', 'koolmind_facebook_post_article');
add_action('new_to_publish', 'koolmind_facebook_post_article');
function koolmind_facebook_post_article( $post_id ) {
require_once 'facebook/facebook.php';
/* some code here */
//verify post is not a revision
if ( !wp_is_post_revision( $post_id ) ) {
$post_title = get_the_title( $post_id );
$post_url = get_permalink( $post_id );
$post_excerpt = get_the_excerpt();
$post_image = 'http://.../default.jpg'; //default image
if( $thumb_id = get_post_thumbnail_id( $post_id ) ){
$image_attributes = wp_get_attachment_image_src( $thumb_id );
$post_image = $image_attributes[0];
}
/* some code here */
}
}让我解释一下这个问题:
如果我使用这3个钩子,我没有问题,但代码是在我的特色图像存储到数据库之前执行的,所以$post_image总是等于默认映像。
如果我使用publish_post钩子,功能图像就会被正确设置(可能是因为这个钩子是在保存了所有数据之后调用的),但是如果我更新我的帖子(wp_is_post_revision似乎不会被触发),我无法避免将数据发送到Facebook。
希望你有个好主意。现在代码几乎没问题!:)
发布于 2013-08-14 17:46:25
'save_post‘钩'在将数据保存到数据库后运行。’。这意味着您可以进行以下验证:
//WP hook
//the last parameter 2 means you pass 2 variables to the callback:
//the ID and the post WP object
add_action( 'save_post', 'koolmind_facebook_post_article',3,2 );
//Callback
function koolmind_facebook_post_article( $post_id, $post ) {
// Validation:
//If current WP user has no permissions to edit posts: exit function
if( !current_user_can('edit_post', $post_id) ) return;
//If is doing auto-save: exit function
if( defined('DOING_AUTOSAVE') AND DOING_AUTOSAVE ) return;
//If is doing auto-save via AJAX: exit function
if( defined( 'DOING_AJAX' ) && DOING_AJAX ) return;
//If is a revision or an autosave version or anything else: exit function
if( $post->post_status != 'publish') return;
/* configuration of facebook params */
/* invoke my code to publish on facebook */
}对我起作用了。
发布于 2012-12-30 09:38:44
试着使用:
add_action('publish_post', 'koolmind_facebook_post_article');https://stackoverflow.com/questions/14089684
复制相似问题