• Resolved uili

    (@uili)


    I’m trying to create a redirection after a webhook is triggered on my site, that create a custom post in wordpress.. could not find any function nativaly from Rank Math that could work how i want so i’m doing using $wpdb. But this way some stufs like number of access are not been counted and cant categorize that redirection too.. this is what I did so far.. is there a better way to do this?

    
    //get the unique course ID
    $course = get_post_meta($post_id, 'course_id', true);
    //get the course permalink
    $permalink = get_permalink($post_id);
    
    //prepare the source
    $source = array([
            'ignore'     => 'case',
            'pattern'    => $course,
            'comparison' => 'exact',
        ]
    );
    
    //prepare the args
    $rank_redirect = array(
        'custom_id'   => $course,
        'sources'     => serialize($source),
        'url_to'      => $permalink,
        'header_code' => '301',
        'status'      => 'active',
        'created'     => current_time( 'mysql' )
    );
    
    global $wpdb;
    $dbname = $wpdb->dbname;
    $rank_math_redirections = $wpdb->prefix . "rank_math_redirections";
    
    //because there is no column named custom_id in wp_rank_math_redirections, we create if doesn't exist so we can use it to insert or update the redirection later
    $is_status_col = $wpdb->get_results(  "SELECT <code>COLUMN_NAME</code> FROM <code>INFORMATION_SCHEMA</code>.<code>COLUMNS</code>    WHERE <code>table_name</code> = '{$rank_math_redirections}' AND <code>TABLE_SCHEMA</code> = '{$dbname}' AND <code>COLUMN_NAME</code> = 'custom_id'"  );
    
    if( empty($is_status_col) ):
        $add_status_column = "ALTER TABLE <code>{$rank_math_redirections}</code> ADD <code>custom_id</code> VARCHAR(50) NULL DEFAULT NULL AFTER <code>id</code>; ";
        $wpdb->query( $add_status_column );
    endif;
    
    $result = $wpdb->update($rank_math_redirections, $rank_redirect, array('custom_id' => $course));
    //If nothing found to update, it will try and create the record.
    if ($result === FALSE || $result < 1) {
        $wpdb->insert($rank_math_redirections, $rank_redirect);
    }
    
    • This topic was modified 2 years, 9 months ago by uili.
    • This topic was modified 2 years, 9 months ago by uili.
Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Create redirection programatically’ is closed to new replies.