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/'

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

    Random posts

    Home
    Search
    Bookmark