我正在尝试将帖子内容中的第一个链接添加到自定义字段。有些事情是错的,我一直试图让它发挥作用,但没有运气。如何将链接添加到“链接”自定义字段?
add_action( 'publish_post', 'check_post' );
function check_post( $post_id ) {
$user_info = get_userdata(1);
function get_first_link() {
global $post, $posts;
preg_match_all('/href\s*=\s*[\"\']([^\"\']+)/', $post->post_content, $links);
return $links[1][0];
}
$first_link = get_first_link();
add_post_meta($post_id, 'link', $first_link, true);
add_post_meta($post_id, 'users', $user_info->user_login, true);
}
EDIT 我让它在中途工作。它会保存网址,但在发布帖子时不保存。它会在更新时保存。我需要使用什么?我尝试使用publish_post,但也保存了更新的URL。
add_action( 'save_post', 'my_save_post', 10, 2 );
function my_save_post( $post_id, $post ) {
if ( wp_is_post_revision( $post_id ) )
return;
$matches = array();
preg_match_all( '/href\s*=\s*[\"\']([^\"\']+)/', $post->post_content, $matches );
$first_link = false;
if ( ! empty( $matches[1][0] ) )
$first_link = $matches[1][0];
$user_info = get_userdata(1);
$meta_link = $_POST['link'];
$args = array(
'post__not_in'=> array($id),
'post_type' => 'post',
'post_status' => array('publish'),
'meta_query' => array(
array(
'key' => 'link',
'value' => $first_link,
'compare' => '='
)
)
);
$existingMeta = get_posts( $args );
if(empty($existingMeta)){
//Go ahead and save meta data
update_post_meta( $post_id, 'link', esc_url_raw( $first_link ) );
update_post_meta($post_id, 'users', $user_info->user_login);
}else{
//Revert post back to draft status
update_post_meta( $post_id, 'link', $existingMeta[0]->ID );
update_post_meta($existingMeta[0]->ID, 'users', $user_info->user_login);
//Now perform checks to validate your data.
//Note custom fields (different from data in custom metaboxes!)
//will already have been saved.
$prevent_publish= true;//Set to true if data was invalid.
if ($prevent_publish) {
// unhook this function to prevent indefinite loop
remove_action('save_post', 'my_save_post');
// update the post to change post status
wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
}
}
}
答案 0 :(得分:1)
你走了:
add_action( 'save_post', 'my_save_post', 10, 2 );
function my_save_post( $post_id, $post ) {
if ( wp_is_post_revision( $post_id ) )
return;
$matches = array();
preg_match_all( '/href\s*=\s*[\"\']([^\"\']+)/', $post->post_content, $matches );
$first_link = false;
if ( ! empty( $matches[1][0] ) )
$first_link = $matches[1][0];
update_post_meta( $post_id, 'link', esc_url_raw( $first_link ) );
}