在wordpress中更改slug时出现致命错误

时间:2012-08-08 16:02:07

标签: php wordpress wordpress-theming permalinks slug

我想用自定义字段更改帖子的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秒的最大执行时间”。但它似乎有效,因为我的slu change改变了。对这个问题有什么看法吗?

1 个答案:

答案 0 :(得分: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...
}