Как добавить на сайт форму добавления в базу данных Knowledge Base (basepress) для пользователей, чтобы сразу создался черновик
1 шаг: на сайте добавим кнопку вывода
Куда вставлять код кнопки:
- В шаблон базы знаний (например, single-knowledgebase.php)
- В header.php или footer.php (для отображения на всех страницах)
- В виджет через PHP Code Widget
- В конкретную страницу через шорткод (нужен дополнительный код)<?php function is_mobile_device() { return wp_is_mobile(); // встроенная функция WordPress } if (!is_mobile_device()) { echo '<button class="baton" id="open-kb-submit-modal" style=" margin: 0 0 15px 0; display: block; ">Предложить тему</button>'; } ?>2 шаг: В файл functions.php обработка и форма
Уберите в коде пробел в тегах < script
// --- Форма для кнопки Предложить тему --- add_action('wp_footer', 'kb_guest_modal_only'); function kb_guest_modal_only() { if (is_admin()) return; echo ' <div id="kb-modal" style="display:none; position:fixed; z-index:99999; left:0; top:0; width:100%; height:100%; overflow:auto; background-color:rgba(0,0,0,0.6); align-items:center; justify-content:center;"> <div class="bo" style="background:#fff; margin:5% auto; padding:20px; border-radius:8px; width:90%; max-width:600px; position:relative; box-shadow:0 5px 15px rgba(0,0,0,0.3);"> <div class="kb-modal-header" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px; border-bottom:1px solid #eee; padding-bottom:10px;"> <h3 style="margin:0; font-size:18px;">Предложить новую тему</h3> <button id="close-kb-modal" class="close-kb-modal" style="background:none; border:none; font-size:24px; cursor:pointer; line-height:1; color:#aaa;">×</button> </div> <div id="kb-modal-form"> <label style="display:block; margin-bottom:5px; font-weight:bold;">Заголовок:</label> <input type="text" id="kb_title" maxlength="100" placeholder="От 5 символов" style="width:100%; padding:8px; margin-bottom:10px; box-sizing:border-box;"> <label style="display:block; margin-bottom:5px; font-weight:bold;">Содержание:</label> <textarea id="kb_content" rows="5" maxlength="2000" placeholder="Без ссылок, от 20 символов..." style="width:100%; padding:8px; margin-bottom:10px; box-sizing:border-box;"></textarea> <button type="button" id="kb_send" class="baton" style="padding:10px 20px; background:#0073aa; color:#fff; border:none; border-radius:4px; cursor:pointer;">Отправить</button> <div id="kb_msg" style="margin-top:10px; font-size:14px;"></div> </div> </div> </div>'; ?> < script> document.addEventListener('DOMContentLoaded', function() { const modal = document.getElementById("kb-modal"); const closeBtn = document.getElementById("close-kb-modal"); const sendBtn = document.getElementById("kb_send"); const msgBox = document.getElementById("kb_msg"); if (!modal || !closeBtn) return; function openModal() { modal.style.display = "flex"; document.body.style.overflow = "hidden"; } function closeModal() { modal.style.display = "none"; document.body.style.overflow = ""; } document.addEventListener('click', function(e) { if (e.target.id === 'open-kb-submit-modal' || e.target.classList.contains('baton') && e.target.id === 'open-kb-submit-modal') { e.preventDefault(); openModal(); } if (e.target.id === 'close-kb-modal') { closeModal(); } if (e.target === modal) { closeModal(); } }); if (sendBtn) { sendBtn.addEventListener("click", function() { const tInput = document.getElementById("kb_title"); const cInput = document.getElementById("kb_content"); if (!tInput || !cInput) return; const t = tInput.value.trim(); const c = cInput.value.trim(); if (t.length < 5 || c.length < 20) { msgBox.innerHTML = "<span style=\"color:red;\">Заголовок от 5 символов, текст от 20 символов.</span>"; return; } sendBtn.disabled = true; sendBtn.textContent = "Отправка..."; fetch("<?php echo admin_url('admin-ajax.php'); ?>", { method: "POST", headers: {"Content-Type": "application/x-www-form-urlencoded"}, body: "action=kb_handle_simple&kb_title=" + encodeURIComponent(t) + "&kb_content=" + encodeURIComponent(c) + "&nonce=<?php echo wp_create_nonce('kb_simple'); ?>" }) .then(function(r) { return r.json(); }) .then(function(d) { if (d.success) { msgBox.innerHTML = "<span style=\"color:green;\">Тема отправлена на модерацию!</span>"; setTimeout(function() { closeModal(); msgBox.innerHTML = ""; tInput.value = ""; cInput.value = ""; }, 2000); } else { msgBox.innerHTML = "<span style=\"color:red;\">Ошибка: " + (d.data && d.data.message ? d.data.message : "Неизвестная ошибка") + "</span>"; } }) .catch(function() { msgBox.innerHTML = "<span style=\"color:red;\">Ошибка соединения.</span>"; }) .finally(function() { sendBtn.disabled = false; sendBtn.textContent = "Отправить"; }); }); } }); </ script> <?php } add_action('wp_ajax_kb_handle_simple', 'kb_handle_simple_submit'); add_action('wp_ajax_nopriv_kb_handle_simple', 'kb_handle_simple_submit'); function kb_handle_simple_submit() { if (!wp_verify_nonce($_POST['nonce'] ?? '', 'kb_simple')) { wp_send_json_error(array('message' => 'Недопустимый запрос.')); } $title = sanitize_text_field(trim($_POST['kb_title'] ?? '')); $content = trim($_POST['kb_content'] ?? ''); if (strlen($title) < 5 || strlen($content) < 20) { wp_send_json_error(array('message' => 'Заголовок от 5 символов, текст от 20 символов.')); } $content = wp_strip_all_tags($content); $content = preg_replace('/https?:\/\/\S+/i', '[ссылка удалена]', $content); $content = preg_replace('/\S+@\S+\.\S+/i', '[email удалён]', $content); $post_id = wp_insert_post(array( 'post_title' => $title, 'post_content' => $content, 'post_type' => 'knowledgebase', 'post_status' => 'draft', 'post_author' => 1, )); if (is_wp_error($post_id)) { wp_send_json_error(array('message' => 'Не удалось создать тему.')); } wp_send_json_success(array('message' => 'Тема отправлена на модерацию.')); } // --- Форма для кнопки Предложить тему --- //
Пример формы из кода выше:
Как добавить на сайт форму добавления в базу данных Knowledge Base

Как добавить на сайт форму добавления записей для пользователей, чтобы сразу создался черновик
https://zaplata.ru/forum/scripts/formu-dobavleniya-srazu-sozdalsya-chernovik