Using a global variable in a wordpress hook, it will not work.

[ad_1]

Hi

​

I’m creating my first WordPress plugin which creates pages on plugin activation, it gets these pages from an array which holds the page title and page content.

​

My issue is that I want to stop access to those pages if you’re not an admin and also remove the pages if the plugin is deactivated and I use a separate function for each of these.

​

Rather than adding the page array 3 times, I wanted to hold it at the top so that if I edit the page names etc I only need to do this once.

​

I people don’t like using global variables but in this case I thought that it must be the best option.

​

To keep everything simple, I’ve added some basic code below. I get no errors when activating the plugin but the page isn’t getting created. If I replace \`\`\`$pageTitle\`\`\` from the ‘title’ => $pageTitle and \`\`\`’post\_title’ => $pageTitle\`\`\` lines with \`\`\`Jumbo \`\`\` the page is created.

​

\`\`\`

$pageTitle = ‘Jumbo’; // The title of the page you want to check or create

​

register\_activation\_hook(\_\_FILE\_\_, ‘hhhh’);

​

function hhhh($pageTitle) {

echo $pageTitle;

// Set up the arguments for the query

$args = array(

‘post\_type’ => ‘page’,

‘post\_status’ => ‘publish’,

‘posts\_per\_page’ => 1,

‘title’ => $pageTitle // Note: ‘post\_title’ changed to ‘title’ for WP\_Query

);

​

// Perform the query

$query = new WP\_Query($args);

​

// Check if the page exists

if (!$query->have\_posts()) {

// If the page doesn’t exist, create it

$my\_post = array(

‘post\_title’ => $pageTitle,

‘post\_content’ => ‘Your page content here’, // Adjust content as needed

‘post\_status’ => ‘publish’,

‘post\_author’ => 1,

‘post\_type’ => ‘page’,

);

​

// Insert the page into the database

wp\_insert\_post($my\_post);

}

​

// Reset post data to avoid conflicts

wp\_reset\_postdata();

}

​

\`\`\`

​

Why is this?

[ad_2]
1 Comment

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer