Skip to content

Instantly share code, notes, and snippets.

@verfasor
Last active March 10, 2023 04:01
Show Gist options
  • Select an option

  • Save verfasor/a5acde039a35efa21255ef62109f4768 to your computer and use it in GitHub Desktop.

Select an option

Save verfasor/a5acde039a35efa21255ef62109f4768 to your computer and use it in GitHub Desktop.
Bring your own key setup for AI Engine WordPress plugin
// Add this to the top of your functions.php file
// WP Session
function register_my_session(){
if( !session_id()){
session_start();
}
}
add_action('init', 'register_my_session');
// Form input
function my_input_field() {
$output = '<div class="keyholder"><input type="text" placeholder="Add or update your own OpenAI Key" name="my_input" id="my_input" value="' . esc_attr( $_SESSION['my_input'] ) . '" /></div>';
echo $output;
}
// Show them the API key in next line (optional)
function display_my_input_value() {
if ( isset( $_SESSION['my_input'] ) ) {
echo '<p>The value you entered is: ' . esc_html( $_SESSION['my_input'] ) . '</p>';
}
}
// Save input
function save_my_input() {
if ( isset( $_POST['my_input'] ) ) {
$_SESSION['my_input'] = sanitize_text_field( $_POST['my_input'] );
}
}
add_action( 'init', 'save_my_input' );
// MWAI filter
add_filter( 'mwai_ai_query', function ( $query ) {
$randomApiKey = $_SESSION['my_input'];
$query->setApiKey( $randomApiKey );
return $query;
}, 10, 2 );
@verfasor
Copy link
Copy Markdown
Author

verfasor commented Mar 9, 2023

Below is the PHP hook that you should inject to the pages where the AI assistant is located.
Apply CSS accordingly.

<p class="keyinfo">Please add or update your own <a href="https://platform.openai.com/account/api-keys">OpenAI API Key</a> below <strong>and press enter</strong>.</p>

<form class="keyform" method="post">
    <?php my_input_field(); ?>
    <!--<button type="submit">Submit</button>-->
</form>

<div class="keyvalue"><?php display_my_input_value(); ?></div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment