'publish', 'posts_per_page' => -1]);
// Get all categories (for other parts of the form).
$categories = get_categories();
// Get all published pages sorted by title.
$pages = get_posts([
'post_status' => 'publish',
'posts_per_page' => -1,
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC'
]);
// Get all published posts sorted by title.
$posts_for_dropdown = get_posts([
'post_status' => 'publish',
'posts_per_page' => -1,
'post_type' => 'post',
'orderby' => 'title',
'order' => 'ASC'
]);
// Concatenate pages and posts to create a single list.
$posts_and_pages = array_merge($pages, $posts_for_dropdown);
// Begin HTML rendering for the admin page.
?>
0) {
// Add links to a single post.
internal_links_plugin_add_links_to_post($post_id, $heading_text, $include_pillar, $pillar_post_id);
} elseif ($category_id > 0) {
// Add links to all posts in the selected category.
$posts_in_category = get_posts(['category' => $category_id, 'posts_per_page' => -1]);
foreach ($posts_in_category as $post) {
internal_links_plugin_add_links_to_post($post->ID, $heading_text, $include_pillar, $pillar_post_id);
}
}
// Redirect to the same page with a success message.
wp_redirect(add_query_arg('success', '1', menu_page_url('internal-links-plugin', false)));
exit; // Ensure the redirection takes place.
}
}
// Function to add links to a specific post.
function internal_links_plugin_add_links_to_post($post_id, $heading_text, $include_pillar, $pillar_post_id) {
$post = get_post($post_id);
if ($post) {
$category_ids = wp_get_post_categories($post_id);
$related_posts = get_posts([
'category__in' => $category_ids,
'exclude' => [$post_id],
'posts_per_page' => 6,
'orderby' => 'rand'
]);
$html = '' . esc_html($heading_text) . '
';
// Include the selected Pillar Post/Page as a bolded item if the on/off checkbox is checked.
if ($include_pillar && $pillar_post_id > 0) {
$pillar_post = get_post($pillar_post_id);
if ($pillar_post) {
$html .= sprintf(
'- %s
',
esc_url(get_permalink($pillar_post->ID)),
esc_html($pillar_post->post_title)
);
}
}
// Continue with adding the list of randomly selected articles.
foreach ($related_posts as $related_post) {
$html .= sprintf(
'- %s
',
esc_url(get_permalink($related_post->ID)),
esc_html($related_post->post_title)
);
}
$html .= '
';
// Append the HTML to the post content and update the post.
$post->post_content .= $html;
wp_update_post($post);
}
}
// Display a success message after adding links.
function internal_links_plugin_admin_notices() {
// Only display the success message on the plugin's settings page.
if (isset($_GET['success']) && isset($_GET['page']) && $_GET['page'] === 'internal-links-plugin') {
echo 'Internal links have been added successfully.
';
}
}
add_action('admin_notices', 'internal_links_plugin_admin_notices');
?>