Random Posts 2 Posts connections

A code snippet to quickly generate random p2p connections.

The problem

I have to work with the never praised enough Posts 2 Posts plugin and did incur in the necessity to generate connections for testing purposes.

A solution

The code snippet below, copied and pasted in a “Must Use” plugin file, will generate some random connection on each page reload.



    if ( ! function_exists( 'connect_some_to_some' ) ) {
        function connect_some_to_some( $n, $from_post_type, $to_post_type, $connection_type ) {
            if ( ! function_exists( 'p2p_type' ) ) {
                return;
            }

            $from_ids = array();
            $to_ids   = array();

            if ( is_array( $n ) ) {
                if ( count( $n ) !== 2 ) {
                    return;
                }
                $from_ids = $n[0];
                $to_ids   = $n[1];
                if ( count( $from_ids ) != count( $to_ids ) ) {
                    return;
                }

                $from_ids = shuffle( $from_ids );
                $to_ids   = shuffle( $to_ids );
            } else {

            $from_ids = get_random_post_ids( $n, $from_post_type );
            $to_ids   = get_random_post_ids( $n, $to_post_type );
            }

            $size = min( count( $from_ids ), count( $to_ids ) );

            for ( $i = 0; $i connect( $from_ids[ $i ], $to_ids[ $i ] );
                }
            }
        }

        function get_random_post_ids( $n, $post_type = 'post' ) {
            global $wpdb;

            $query = $wpdb->prepare( "SELECT p.ID FROM sls_posts p WHERE p.post_type = %s AND post_status = 'publish' ORDER BY RAND(%d) LIMIT %d", $post_type, rand(), $n );

            return $wpdb->get_col( $query );
        }
    }

    add_action( 'shutdown', function () {
        connect_some_to_some( 100, 'post', 'person', 'citation' );
    } );

I appreciate your input