This is not how variables work in PHP. You’re using them before they are defined. They’re not templates that will be replaced later. If you want to use those variables in $new_post
then you need to define $new_post
inside your loop after those variables are defined.
function mic_create_new_page() {
global $user_ID, $wpdb;
$tableau_post = array ();
$tableau_post = mic_stock_in_array($tableau_post);
$res = $wpdb->get_results('select * from wp_secteurs');
foreach ( $res as $ville ) {
$id = $ville->id_secteurs;
$secteur = $ville->libelle;
$slugmic = strtolower( str_replace( " ", "-", $secteur ) ) . "-s" . $id;
$new_post = array(
'post_title' => 'Service ' . $secteur,
'post_content' => '[makeitseo-keyword]',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author ' => $user_ID,
'post_type' => 'page',
'post_name' => $slugmic
);
if ( ! in_array( normalize( $slugmic ), $tableau_post ) ) {
$post_id = wp_insert_post( $new_post );
}
}
}
There’s a few code smells in your code that stick out to me that I also want to point out:
Firstly, you’re relying on a global variable, $user_ID
. This is a bad idea because now your function is overly reliant on the global state, which makes its results unpredictable and hard to test. You should pass in the user ID as an argument to the function from somewhere where it’s reliably defined as the user you want to use. For example, if you want to create this page whenever a user is registered using the user_register
hook, then you should use the user ID that is passed into its callbacks:
function mic_create_new_page( $user_id ) {
// Now $user_id is guaranteed to be the ID of the user being registered.
}
add_action( 'user_register', 'mic_create_new_page' );
Secondly, I can’t figure out what this is supposed to do:
$tableau_post = array ();
$tableau_post = mic_stock_in_array($tableau_post);
I can’t think of any reason why you’d initialise a variable like this, then pass it into a function only to replace the variable. I don’t know enough about the code to offer any suggestions though, but I can’t see any reason why just this wouldn’t work:
$tableau_post = mic_stock_in_array( array() );
But I suspect you might not even need all of that.