0

我想用自定义字段更改帖子的 slug。

例如,如果自定义字段是“关键字”,我的帖子链接将变为:mysite.com/keyword。

我在 fonction.php 中编写了这个脚本:

function change_default_slug($id) {

    // get part number
    $partno = get_post_meta( $id, 'partno', true );
    $post_to_update = get_post( $id );

    // prevent empty slug, running at every post_type and infinite loop
    if ( $partno == '' )
        return;

    $updated_post = array();
    $updated_post['ID'] = $id;
    $updated_post['post_name'] = $partno;
    wp_update_post( $updated_post ); // update newly created post

}
add_action('save_post', 'change_default_slug');
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
    add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'normal', 'high' );
}

function cd_meta_box_cb( $post )
{
    $values = get_post_custom( $post->ID );
    $text = isset( $values['my_meta_box_text'] ) ? esc_attr( $values['my_meta_box_text'][0] ) : '';
    wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
    ?>
    <p>
        <label for="my_meta_box_text">Text Label</label>
        <input type="text" name="my_meta_box_text" id="my_meta_box_text" value="<?php echo $text; ?>" />
    </p>
    <?php   
}
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
    // Bail if we're doing an auto save
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    // if our nonce isn't there, or we can't verify it, bail
    if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;

    // if our current user can't edit this post, bail
    if( !current_user_can( 'edit_post' ) ) return;

    // now we can actually save the data
    $allowed = array( 
        'a' => array( // on allow a tags
            'href' => array() // and those anchords can only have href attribute
        )
    );

    // Probably a good idea to make sure your data is set
    if( isset( $_POST['my_meta_box_text'] ) )
        update_post_meta( $post_id, 'my_meta_box_text', wp_kses( $_POST['my_meta_box_text'], $allowed ) );
}
 $partno = get_post_meta($post->ID,'my_meta_box_text',true);
 echo $partno;

该脚本返回“致命错误:超过 30 秒的最大执行时间”。但它似乎有效,因为我的 slug 改变了。对这个问题有任何想法吗?

4

1 回答 1

0

'save_post' 操作由 调用wp_update_post(),因此您的change_default_slug()函数会导致无限循环。change_default_slug()如果该函数已被调用,您需要在内部执行检查并退出:

function change_default_slug($id) {
    static $beentheredonethat = false;
    if ($beentheredonethat) return;
    $beentheredonethat = true;
    //do your stuff and save the post...
}
于 2012-08-08T16:30:40.063 回答