WordPress

Change the permalink structure of WordPress on the Unit testing

When we want to test a permalink of WordPress, sometimes, we need to update the settings of permalink in WordP […]

広告ここから
広告ここまで

When we want to test a permalink of WordPress, sometimes, we need to update the settings of permalink in WordPress.
Because the WordPress running on the PHPUnit might be the default.

For example, we can create post by using factory->post->create_and_get method.

class Example_Test extends \WP_UnitTestCase {
    public function test_it() {
        $post = $this->factory->post->create_and_get( array(
            'post_status' => 'publish',
            'post_name' => 'hello-world',
        ) );
        $this->assertEquals( 'test', get_permalink( $post ) );
    }
}

And the result it here.

--- Expected
 +++ Actual
 @@ @@
 -'test'
 +'http://localhost:8889/?p=4'

The post’s permalink is localhost:8889/?p=4. It’s due to the default rule of WordPress.

Use $wp_rewrite to update the permalink

We can update the permalink by using $wp_rewrite.

class Example_Test extends \WP_UnitTestCase {
    public function setUp() {
        /** @var WP_Rewrite $wp_rewrite */
        global $wp_rewrite;

        parent::setUp();

        /**
         * Change the permalink structure
         */
        $wp_rewrite->init();
        $wp_rewrite->set_permalink_structure( '/%postname%/' );
    }
    public function test_it() {
        $post = $this->factory->post->create_and_get( array(
            'post_status' => 'publish',
            'post_name' => 'hello-world',
        ) );
        $this->assertEquals( 'test', get_permalink( $post ) );
    }
}

Then, we can get an updated permalink of the post.

--- Expected
 +++ Actual
 @@ @@
 -'test'
 +'http://localhost:8889/hello-world/'

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts