{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \"; \n wp_mail( \"nabestan98@gmail.com\", \"دریافت نامه کاربر\", $body, $headers , array($attachment_img) );\n }"},"RESPONSE":{"kind":"string","value":"I changed the code to this and it worked ! Don't know why I should do this and this is very odd but whatever.\n \n \n function send_mail_to_admin($orderId , $attachment_img){\n $attachment_img = str_replace(\" , \"\" , $attachment_img);\n $attachment_img = array( WP_CONTENT_DIR . $attachment_img );\n $headers = array('Content-Type: text/html; charset=UTF-8','From: انجمن آبزیان ');\n $body = \"\n یک مشتری سفارش با شماره $orderId ثبت کرد\n \"; \n wp_mail( \"nabestan98@gmail.com\", \"دریافت نامه کاربر\", $body, $headers , $attachment_img );\n }"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"plugins, php, directory, wp mail\"\n}"}}},{"rowIdx":6330609,"cells":{"INSTRUCTION":{"kind":"string","value":"How to send variable to wp meta_query value?\nI try to to make compare by company title so I need to send this title as variable to meta query value. I use this code and get value = NULL. Please tell me why?\n \n \n $company_name = the_title( );\n $params = array(\n 'meta_query' => array(\n array( \n 'key' => 'user_company',\n 'value' => $company_name\n )\n )\n );"},"RESPONSE":{"kind":"string","value":"Use `get_the_title` to get the title. `the_title` is for when you want to output directly to the browser."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"meta query\"\n}"}}},{"rowIdx":6330610,"cells":{"INSTRUCTION":{"kind":"string","value":"Get term from multiple taxonomy\nI am trying to show all the terms from these taxonomies. However, I can't get them working. Please help, thanks\n \n \n array(\n 'category',\n 'profile_status',\n 'profile_skill')\n );\n \n if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){\n echo '
    ';\n foreach ( $terms as $term ) {\n echo '
  • ' . $term->name . '
  • ';\n }\n echo '
';\n }\n \n ?>"},"RESPONSE":{"kind":"string","value":"Your `get_terms` is causing a parse error, you are missing the array part.\n\nAlso when using `get_terms` take into account that by default it will not return taxonomies that don't have posts attached to them.\n\nThe proper code would be like this\n \n \n $terms = get_terms([\n 'taxonomy' => [\n 'category',\n 'profile_status',\n 'profile_skill'\n ]\n ]);\n \n\nIf you want to include empty taxonomies (taxonomies without posts attached to them), do this\n \n \n $terms = get_terms([\n 'taxonomy' => [\n 'category',\n 'profile_status',\n 'profile_skill'\n ],\n 'hide_empty' => false\n ]);"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"taxonomy, terms\"\n}"}}},{"rowIdx":6330611,"cells":{"INSTRUCTION":{"kind":"string","value":"hide elements of admin with css file\ni use woocommerce and woocommerce Product Vendors (< i want hide elements of admin with css file \"my-admin.css\" I put css file \"my-admin.css\" at the root of my child theme wordpress and use this code in functions.php. This does not work?!?\n \n \n function admin_css() {\n $admin_handle = 'admin_css';\n $admin_stylesheet = get_template_directory_uri() . 'my-admin.css';\n \n wp_enqueue_style($admin_handle, $admin_stylesheet);\n }\n add_action('admin_print_styles', 'admin_css', 11);\n \n\nis this an obselete method? because: when i use this other method in functions.php, it's ok it works add_action('admin_head', 'my_custom_fonts');\n \n \n function my_custom_fonts() {\n echo '';\n }\n \n\nWhat do you think ? thanks !!! :)"},"RESPONSE":{"kind":"string","value":"It's always better to encapsulate your styles in a separate file, so your first example is closer. That said, the documentation for admin_print_styles says quite clearly:\n\n> admin_print_styles should not be used to enqueue styles or scripts on the admin pages. Use admin_enqueue_scripts instead."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"admin, admin css\"\n}"}}},{"rowIdx":6330612,"cells":{"INSTRUCTION":{"kind":"string","value":"make admin.css in my child theme\ni want hide elements of admin with css file \"my-admin.css\" I put css file \"my-admin.css\" at the root of my child theme wordpress and use this code in functions.php\n\nbut does not work?\n\nthere may be an error?\n\nthank you ! :\n \n \n ' . wp_count_posts()->publish . '';\n return $args;\n }\n add_filter( 'wp_list_categories', 'cat_list_show_all', 10, 2 );\n \n\nBut, it return \"Array\" on front-end. What's the right way to do it?"},"RESPONSE":{"kind":"string","value":"The documentation for the `wp_list_categories` filter says that it:\n\n> Filters the HTML output of a taxonomy list.\n\nSo it filters the final HTML, not the args, but you're returning `$args`, which means that the final HTML is replaced with the args array. That's why you're seeing \"Array\".\n\nTo filter the args for the categories list in the Categories widget, you need to use the `widget_categories_args` filter.\n \n \n function cat_list_show_all( $args ) {\n $args['show_option_all'] = __( 'All Cateogries', 'textDomain' ) . '' . wp_count_posts()->publish . '';\n return $args;\n }\n add_filter( 'widget_categories_args', 'cat_list_show_all' );\n \n\nHowever, be aware that this filter only works for the \"legacy\" Categories widget. Newer sites will only have access to the Categories _block_. The Categories block does not have an equivalent filter, so filtering the args is not possible."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"categories, filters\"\n}"}}},{"rowIdx":6330615,"cells":{"INSTRUCTION":{"kind":"string","value":"Multisite login - registration is duplicated\nI am running a Multisite installation of Wordpress that runs WooCommerce. There six subsites, three of which are a traditional B2C retail and another three that are B2B Wholesale. Anybody can access the B2C (they are territory dependent), create an account and transact. The B2B is different; we manually create the accounts for our Wholesale customers.\n\n * **B2C** \\- www.domain.com/my-account\n * **B2B** \\- www.domain.com/wholesale/my-account\n\n\n\nSo we have have noticed that if the Wholesale customer goes to the B2C my account page mistakingly and uses their B2B credentials then they are logged in and a new registration is created there. SO they now have access to both the B2B and B2C sites which can lead to confusion.\n\nHow I can prevent this auto 'dual' login"},"RESPONSE":{"kind":"string","value":"By default WordPress Multisite indeed has a shared user base. So, there is no new registration created in de B2B site. It is simply the same registration for all six sites.\n\nOf course, this can be modified. You could try programming this yourself, but there are plenty plugins that will do this for you. We don't do software recommendations around here, but you could try googling for \"wordpress multisite user management plugin\"."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"woocommerce offtopic, multisite\"\n}"}}},{"rowIdx":6330616,"cells":{"INSTRUCTION":{"kind":"string","value":"Automatic excerpt is not shown with the_excerpt() command\nI've been looking for an answer to this question for a long time, but haven't found anything: how come when I use the_excerpt() on a given site it doesn't automatically print the first few characters of the content?\n\nThe excerpt only prints it if something has been added to the WordPress summary field of the post.\n\nHow can I fix this problem? With other sites this does not happen and if no text is added on the summary the excerpt is generated automatically.\n\nWhat could it be that the excerpt is not automatically generated?\n\nMy situation is similar to this: Automatic Excerpt Not Working\n\nbut your response did not provide me with any advice unfortunately."},"RESPONSE":{"kind":"string","value":"By default, `the_excerpt()`, doesn't uses the post/page content wysiwyg, it has its own textarea, that by default is not visible, you need to enable it first via screen options.\n\n![enter image description here](\n\nAfter you checked this checkbox you can scroll down to the bottom of the post/page and see a new textarea, this is the excerpt.\n\n![enter image description here](\n\nIf you want to use the content (wysiwyg, `the_conetnt()` or `get_the_content()`) as excerpt, you will need to use wp_trim_words. \nSomething like this.\n \n \n // the second argument is how many words to trim, default is 55\n \n \n\nAnothe option, if you want to keep the html structure would be to do this.\n \n \n "},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"php, excerpt\"\n}"}}},{"rowIdx":6330617,"cells":{"INSTRUCTION":{"kind":"string","value":"Conditional Generation of Image Sizes using add_image_size\nThe add_image_size function is used to add image sizes in addition to the default thumbnail, medium, large, & full which are generated in WordPress by default.\n\nIs there any way to only add those image sizes for specific uploads? Or are we limited to generating all possible image sizes for every upload?"},"RESPONSE":{"kind":"string","value":"Take a look at the intermediate_image_sizes_advanced filter. This filter receives the attachment ID in question, so with that you should be able to work out whether or not you want the intermediate sizes, and return an empty array if not."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"plugin development, theme development, images\"\n}"}}},{"rowIdx":6330618,"cells":{"INSTRUCTION":{"kind":"string","value":"Automatically download, install and activate plugins that my plugin depends, how?\nI'm developing a plugin that requires a couple of plugins from WordPress repository to work correctly.\n\nIs it possible to download and install from WordPress repository and activate one or more plugin that my custom plugin requires automatically on plugin activation?\n\nThere is a safe and correct way to do this via PHP?"},"RESPONSE":{"kind":"string","value":"TGMPA is a useful php class to perform the required actions: <"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 1,\n \"tags\": \"plugins, plugin development\"\n}"}}},{"rowIdx":6330619,"cells":{"INSTRUCTION":{"kind":"string","value":"How to change widget title in wordpress version 5.8.1?\nMaybe this is a novice question but I am stumped. I am trying to change the title of a widget (recent posts) in WordPress 5.8.1 version. I have installed WordPress after a long time again and can not seem to find the option to change a widget title. How to do this? Please remember that I do not want to change the title programmatically as I can do that. Just want an easy point and click option like the old WordPress. I have attached a screenshot of the widget admin screen. ![enter image description here]("},"RESPONSE":{"kind":"string","value":"In WordPress 5.8 the ability to add Blocks to widget areas, and several core widgets were replaced with Blocks. Blocks do not have a standardised title field. So to add titles you will need to use a heading bock, and for any blocks that do have a title, whether or how a title can be changed would depend entirely on the block."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"widgets, widget text\"\n}"}}},{"rowIdx":6330620,"cells":{"INSTRUCTION":{"kind":"string","value":"Mass SQL Wordpress Meta Key deletion\nhi i am newbie with SQL data base so forgive my dumbness i have installed KK Star rating plugin on my wp site which noticed its recording lot of entries and my db size is over 280 MB and 188MB is wp_postmeta table. uninstalled the plugin and i want to run sql query to delete all postmeta with kkstar recorcs. the meta key record is: kksr_fingerprint_default so please give me correct command line to run thanks in advance"},"RESPONSE":{"kind":"string","value":"DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default'\n \n\n{PREFIX} is the string `$table_prefix` defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result\n \n \n DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 0,\n \"tags\": \"plugins, post meta, mysql\"\n}"}}},{"rowIdx":6330621,"cells":{"INSTRUCTION":{"kind":"string","value":"Set a specific page as 404 - not found via my own plugin\nI'm developing a plugin that create some pages and set a specific template for each of these pages. It creates a page in which it sets a template for 404 - not found, how can set this specifc page as WordPress 404 (so it will be displayed when needed)?"},"RESPONSE":{"kind":"string","value":"You can filter `404_template` and return the path of your custom file from the plugin directory like this:\n \n \n add_filter( \n '404_template', \n fn() => plugin_dir_path( __FILE__ ) . '404.php' \n );\n \n\nThis hook exists only when a 404 happens, so you don't need any custom detection."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 4,\n \"question_score\": 2,\n \"tags\": \"plugin development, pages, 404 error\"\n}"}}},{"rowIdx":6330622,"cells":{"INSTRUCTION":{"kind":"string","value":"i need to let a user to add a role from a frontend form\ni need to let a registered user who already has role or 2 roles the ability to add himself a role via frontend form. i tried to look for it and didn't find anything related that can help me. any ideas? thanks."},"RESPONSE":{"kind":"string","value":"I think each user can only have one role. However this is how its possible to change role, if for some reason that I dont know the user can have more than one role, remove the remove role line. you can check the available roles here.\n \n \n $current_user = wp_get_current_user();\n // Remove role\n $current_user->remove_role( 'subscriber' );\n // Add role\n $current_user->add_role( 'editor' );"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": -2,\n \"question_score\": 0,\n \"tags\": \"users, user roles\"\n}"}}},{"rowIdx":6330623,"cells":{"INSTRUCTION":{"kind":"string","value":"Get posts that do not have the same tags as current\nI'm trying to get all posts in a custom plugin loop that DO NOT share the same tag as the current one.\n\nI'm trying:\n \n \n $events = tribe_get_events([\n 'start_date' => 'now',\n 'eventDisplay' => 'list',\n 'posts_per_page' => 3,\n 'tag' => $current_tag // <-- Trying to do the exact opposite of this\n ]);\n \n\nI'm using < 's plugin. But under the hood, that just uses the normal WP args setup.\n\nIs there a way to invert the tag selection to get posts that DO NOT have that tag?"},"RESPONSE":{"kind":"string","value":"I found an answer to my own question:\n\nIf I use the `tax_query` arg then I could specify `'operator' => 'NOT IN'` like so:\n \n \n $events = tribe_get_events([\n 'tax_query' => array(\n array(\n 'taxonomy' => 'post_tag',\n 'field' => 'name',\n 'terms' => $current_tag,\n 'operator' => 'NOT IN' // HERE\n )\n ),\n 'start_date' => 'now',\n 'eventDisplay' => 'list',\n 'posts_per_page' => 3,\n ]);"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"wp query, loop, tags, query posts\"\n}"}}},{"rowIdx":6330624,"cells":{"INSTRUCTION":{"kind":"string","value":"How do I include SVG file used as featured image?\nI'm new, can I use include() or get_template_part to load an SVG file uploaded as featured image directly in the HTML page?\n\nI need to animate the svg images, but i need to easily change the image on each page.\n\nI have tried this code but does't work, I can't find the right path, I can load only the svg images in the same folder.\n \n \n $domain = get_site_url();\n $svg_url = get_the_post_thumbnail_url(get_the_ID());\n $svg = str_replace( $domain, '', $svg_url );\n \n echo $svg; //only for read the url\n \n get_template_part($svg);\n // or\n inlcude $svg;"},"RESPONSE":{"kind":"string","value":"First, you don't need the URL but the server path to the file, you can get it with `get_attached_file` function, passing any WordPress attachment ID as a parameter. Then you need to load the contents of that SVG file directly, via `file_get_contents` function and echo it out to the page.\n \n \n $thumbnail_id = get_post_thumbnail_id( get_the_ID() );\n $thumbnail_path = get_attached_file( $thumbnail_id );\n echo file_get_contents( $thumbnail_path );"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"php, svg\"\n}"}}},{"rowIdx":6330625,"cells":{"INSTRUCTION":{"kind":"string","value":"Will I get an error if I try unscheduling a WP Cron scheduled task that wasn't scheduled?\nSo, I'm developing a plugin, I wanted to know if I call\n \n \n $timestamp = wp_next_scheduled( 'scheduled_hook' );\n wp_unschedule_event( $timestamp, 'scheduled_hook' );\n \n\nWithout checking if it's scheduling at all, will it give me an error or will it just go through it and unschedule it in case it is actually scheduled and ignore it otherwise?"},"RESPONSE":{"kind":"string","value":"So yeah, it does give errors for trying to unschedule something that isn't scheduled, but the answer is pretty easy and simple:\n \n \n $timestamp = wp_next_scheduled( 'scheduled_hook' );\n if ($timestamp) wp_unschedule_event( $timestamp, 'scheduled_hook' );\n \n\nSince `wp_next_scheduled` will return false for unscheduled hooks, a simple `if` in front of the call to `wp_unschedule_event` will prevent it from being called it there's nothing scheduled"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"plugin development, wp cron\"\n}"}}},{"rowIdx":6330626,"cells":{"INSTRUCTION":{"kind":"string","value":"Applying WP-cli Search & Replace to Static SQL Dump File\nI have a wp db dump file inside my site directory. Can someone show me an example of how to use wp-cli search and replace command on the static sql file, not the active db to change my url from \"old-example.com\" to \"new-example.com\"\n\n/var/www/html/wp-site.com/dumps/oldexample.com/dumpeddb.sql\n\n/var/www/html/wp-site.com/dumps/newexample.com/ready-for-import.sql\n\nNot quite sure how to apply this to already exported db dump. \n`$wp search-replace foo bar --export=database.sql`"},"RESPONSE":{"kind":"string","value":"This is not possible, WP CLI uses SQL queries to acquire and update information. You would need to import the SQL file into a database to perform a search replace with WP CLI."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"customization, database, search, mysql\"\n}"}}},{"rowIdx":6330627,"cells":{"INSTRUCTION":{"kind":"string","value":"Put featured image under post title in admin area\nInstead of inserting a new column with a featured image on it, I would like to put the featured image under the post's already existing title. I can't seem to figure out how you insert things on the title property however. Achieving this:\n\n![enter image description here](\n\nI've found this post: How can i place Feature Image under title field in wp-admin?\n\nWith a snippet that I can't get to work. Otherwise there are lots of solutions for adding new columns with featured images in them.\n\nI've arrived at something like this:\n \n \n add_action('admin_head-edit.php', function(){\n add_filter('the_title', function( $title, $id ) {\n return $title . get_the_post_thumbnail_url();\n }, 100, 2);\n });\n \n\nBut if I use `get_the_post_thumbnail_url` the url is embedded as part of the title, and if I use `the_post_thumbnail( 'thumbnail' )` it renders the image twice."},"RESPONSE":{"kind":"string","value":"add_action('admin_head-edit.php', function(){\n add_filter('the_title', function( $title, $id ) {\n return $title . the_post_thumbnail( 'thumbnail' );\n }, 100, 2);\n });\n \n\nWill produce 2 images because there are two titles on custom posts, apparently. One that is hidden and one that isn't. Adding the image markup to the hidden element will break the CSS that hides it. So the solution is to insert admin-css that hides it.\n \n \n .column-title .hidden ~ img{\n display: none;\n }"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"custom post types, wp admin, post thumbnails\"\n}"}}},{"rowIdx":6330628,"cells":{"INSTRUCTION":{"kind":"string","value":"Polylang : Display term archive even if no posts\nI use ACF to customize **taxonomy term archives pages** which are in fact **Team member pages**. Pages are translated with the help of Polylang.\n\nProblem is : If the member has no related posts, I can access directly the member page, but the translated page is not linked to the language switcher menu. Instead it has been replaced with a link to translated homepage.\n\nI found that this is common behaviour in Polylang. It is programmed to never show translated pages with no posts.\n\nAfter some research, if found this filter that might be helping. It has been added a while ago but there is no sign of it in the Polylang documentation.\n\nAnybody knows how to use is ?\n\nThanks"},"RESPONSE":{"kind":"string","value":"Solution given by filter author :\n \n \n add_filter( 'pll_hide_archive_translation_url', '__return_false' );"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"terms, custom post type archives, plugin polylang\"\n}"}}},{"rowIdx":6330629,"cells":{"INSTRUCTION":{"kind":"string","value":"Display Current Date using shortcode\nI am using the below code to display current date in php using shortcodes for Indian time zones:\n \n \n add_shortcode( 'current_date', 'mth_footer_date2' );\n function mth_footer_date2() {\n ob_start();\n date_default_timezone_set(\"Asia/Kolkata\");\n echo gmdate(\"jS F Y\");\n return ob_get_clean();\n }\n \n\nWe need to add `[current_date]` Shortcode to display current date. This code is displaying date but I think, this is not in Indian Timezone. Please provide me such codes to display time in Indian Timezone. I want Date in following format, **Sunday, 24th October, 2021**.\n\nAlso provide ways to show tomorrow date in same format."},"RESPONSE":{"kind":"string","value":"You need to use `date()` in place of `gmdate()`, which returns the date/time for GMT.\n\nTo get the output you want, change the code to:\n \n \n echo date('l, jS F, Y');\n \n\nFor displaying tomorrow's date, use the following code accordingly:\n \n \n $timestamp = strtotime('tomorrow');\n echo date('l, jS F, Y', $timestamp);"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"date\"\n}"}}},{"rowIdx":6330630,"cells":{"INSTRUCTION":{"kind":"string","value":"How do I add nopin=\"nopin\" to the default avatar?\nI noticed that if someone clicks on my Pinterest share button on a blog post, several unrelated images show up. I was able to use _nopin= \"nopin\"_ per Pinterest's documentation on most of these images to clean most of it up.\n\nHowever, I have a custom avatar set in my functions.php...\n \n \n //* Add new default gravatar to Settings » Discussion page */\n add_filter( 'avatar_defaults', 'wpb_new_gravatar' );\n function wpb_new_gravatar ($avatar_defaults) {\n $myavatar = '\n $avatar_defaults[$myavatar] = \"Default Gravatar\";\n return $avatar_defaults;\n }\n \n\nIf someone gets that avatar in a comment, then the image shows up as a choice on a Pinterest share. How do I add the _nopin= \"nopin\"_ attribute to this avatar image?\n\nI found a similar post discussing this issue, but it's way over my head and seems a little different because he's using an array (lol, also over my head).\n\nAny help is greatly appreciated!"},"RESPONSE":{"kind":"string","value":"You can try this one:\n \n \n function wp_ste_add_nopin_args( $args ) {\n $extra_attr = 'nopin=\"nopin\"';\n $args['extra_attr'] = $extra_attr;\n return $args;\n }\n add_filter( 'get_avatar_data', 'wp_ste_add_nopin_args', 999, 1 );\n \n\nFor further reading, please visit: <"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"customization, avatar, gravatar\"\n}"}}},{"rowIdx":6330631,"cells":{"INSTRUCTION":{"kind":"string","value":"wp-json how to fetch image link?\ni'm trying to fetch some data and images. everything is working good, but i'm really tired to fetch the post thumbnail image.\n \n \n $data = array(\n ':attachment' => $record['_links']['wp:attachment'][0]['href'],\n );\n \n\nthe above code fetching media link such as ` but i want to fetch like that ` how i can do that? please try with a wordpress website with wp-json to see the structure."},"RESPONSE":{"kind":"string","value":"i already fix this by using this\n \n \n $data = array(\n ':attachment' => $record[_embedded]['wp:featuredmedia']['0'][source_url]\n );\n \n\nthanks for no person answered my question."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"json\"\n}"}}},{"rowIdx":6330632,"cells":{"INSTRUCTION":{"kind":"string","value":"Add attributes to wrapper html generated by wp_nav_menu\nI want to add some extra html attributes to the default div html generated by wp_nav_menu. I need to add simple code for example a short style code: `style=\"top:10px;\"` _I can't do what I am doing in a css file_ ; _the html needs to be added in the php_. I have looked at many examples, of walkers, replacement codes like str_replace. I can't find a solution that functions the way I envision it exactly. I prefer to not use a walker code that is ten pages long php code just for doing this simple code addition. If there is not a simple way, the alternative is to wrap the menu in a second div and that is what I will do probably if I can't find another way; but I would prefer to learn a simple way to add the html code to the original div generated by wp_nav_menu."},"RESPONSE":{"kind":"string","value":"Modifying the wrapper for the `wp_nav_menu()` is customizable with the `items_wrap` parameter. <\n\nThe documentation states that the default wrapper is a `
    ` element with an ID an CLASS attribute. This can be modified as you wish by modifying the markup passed to the `sprintf()` function used by `wp_nav_menu()`.\n\nThe value for `items_wrap` is the argument passed for the wrapper. To output a `
    ` element with a style attribute:\n \n \n wp_nav_menu( array( 'items_wrap' => '
    %3$s
    ' ) );\n \n\nThe `%3$s` in the example represents the items within the wrapper HTML."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"menus, walker\"\n}"}}},{"rowIdx":6330633,"cells":{"INSTRUCTION":{"kind":"string","value":"JSON REST API Wordpress only showing first 10 categories\nAlphabetically ordered categories are shown first (first 10). If I try to show all categories in JSON / Wordpress, it's not showing it.\n\nSo, imagine these are the categories:\n \n \n A\n B\n C\n D\n E\n F\n G\n H\n I\n J\n K (=10)\n L = not shown anymore\n \n\nHow can I make sure I fetch them all?\n\nI am trying to fetch them in Dart via JSON, so I can only pass that to Dart. Is there a way I can achieve this?"},"RESPONSE":{"kind":"string","value":"This is normal behaviour, you've not accounted for pagination. The REST API returns 10 results per page by default, and can be configured to return up to but no more than 100 per page.\n\nYou may be tempted to try `-1`, but this will not work, 100 is the maximum results per page that can be requested for performance and scaling reasons.\n\nWordPress provides 2 http headers indicating the total number of pages, and the total number of results across all pages so that you know how many requests are needed to fetch all results.\n\nI _**strongly**_ recommend reading the REST API handbook in the official documentation. This page covers how to use and control pagination, sorting, etc."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 0,\n \"tags\": \"php, categories, rest api, json\"\n}"}}},{"rowIdx":6330634,"cells":{"INSTRUCTION":{"kind":"string","value":"How to not display tags with less than X posts\nIs there a way to avoid displaying tags which have less than X Posts?\n\nthe answer here is close Remove from Google Tags with less than 2 posts\n\nhowever it suggests to send a respose header to google. I would ideally like to NOT have these tags in my sitemap so that google does not index these pages which are basically duplicates of the original post with a different tag, not a good thing for SEO!"},"RESPONSE":{"kind":"string","value":"Tags don't create duplicate posts, so the likelihood of them hurting your SEO by appearing in a sitemap are slim.\n\nYou can add a filter to the return of the taxonomies sitemap to remove tags. This is just a quick attempt I threw together. I haven't tested it but it should provide a basis to work from at the very least.\n \n \n function remove_low_tags($taxonomies) {\n //create a new array of tags with count above 2\n array $allowed_tags;\n //loop through current array of tags and add them to $allowed_tags if they are > 2\n foreach ($taxonomies as $tags) {\n if (count($tags) > 2) {\n $allowed_tags[] = $tags;\n }\n }\n return $allowed_tags;\n }\n add_filter('wp_sitemaps_taxonomies', 'remove_low_tags');"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 0,\n \"tags\": \"wp query, tags, conditional tags\"\n}"}}},{"rowIdx":6330635,"cells":{"INSTRUCTION":{"kind":"string","value":"I'm getting a 401 while calling the wp-json endpoint via ajax\n**N.B. Resolved - I hadn't noticed it was a POST rather than a GET.**\n\nI'm trying to use an AJAX call from a front end page to pull a list \"Staff\" (custom post type). I can get the data in the browser via wp-json/wp/v2/staff but I get a 401 when I try to pull the data via AJAX. I'm assuming I need to authenticate somehow but can't work out how to to do it.\n\nThanks in advance."},"RESPONSE":{"kind":"string","value":"I had accidentally created a POST rather than a GET. Obviously, you need credentials if you post."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 1,\n \"tags\": \"ajax\"\n}"}}},{"rowIdx":6330636,"cells":{"INSTRUCTION":{"kind":"string","value":"Why would the child theme load in the Customize preview, but not on the site itself?\nI have my child theme folder, the style.css sheet with the required template comment and some custom css, and I have the functions.php page with the required enqueing code.\n\nEverything seems to be in order, except that my custom css is not reflected on my website. However, it _IS_ reflected in the Wordpress Customize screen. Why would this be the case, and how would I get my site to display the custom CSS?"},"RESPONSE":{"kind":"string","value":"It appears to work correctly now, I do not know why emptying the cache didn't work before to allow the changes to show but it seems to work correctly now."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"php, css, child theme, theme customizer, wp enqueue style\"\n}"}}},{"rowIdx":6330637,"cells":{"INSTRUCTION":{"kind":"string","value":"Using a filter to change a path\nI know this is probably basic Wordpress coding but how would I achieve this?\n\n> Use the filter “wcvendors_pro_table_display_rows_path” — and return a path to the new template file. (/plugins/wc-vendors-pro/public/class-wcvendors-pro-table-helper.php Line #328.)\n\nLine #328 of plugins/wc-vendors-pro/public/class-wcvendors-pro-table-helper.php is:\n \n \n public function display_rows() {\n \n include apply_filters( 'wcvendors_pro_table_display_rows_path', 'partials/helpers/table/wcvendors-pro-table-data.php' );\n \n }\n \n\nI have created a duplicate of wcvendors-pro-table-data.php in my child theme."},"RESPONSE":{"kind":"string","value":"Create the template you want to use, say `wc-vp-table-rows.php`, put it in your theme, and add the following to your `functions.php`:\n \n \n add_filter( \n 'wcvendors_pro_table_display_rows_path', \n fn() => locate_template( 'wc-vp-table-rows.php' )\n );\n \n\n`locate_template()` returns a complete path; it also searches in parent and child themes."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 0,\n \"tags\": \"woocommerce offtopic, filters\"\n}"}}},{"rowIdx":6330638,"cells":{"INSTRUCTION":{"kind":"string","value":"How do I override template-tags.php in 2021 theme\nI've created a child theme and I want to overwrite functions in inc/template-tags.php file. I thought if I copy this file and recreate folder structure in my child them then it will work but it doesn't? How to do it properly?"},"RESPONSE":{"kind":"string","value":"Notice how the parent theme checks if they are already defined e.g.\n \n \n if ( ! function_exists( 'twenty_twenty_one_entry_meta_footer' ) ) {\n ...\n }\n \n\nThen just define them in your child theme's `functions.php` file, to override the corresponding template tag.\n\nIt should work because the child theme's `functions.php` file is loaded before the parent's `functions.php` file that loads:\n \n \n // Custom template tags for the theme.\n require get_template_directory() . '/inc/template-tags.php';"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"theme twenty twenty one\"\n}"}}},{"rowIdx":6330639,"cells":{"INSTRUCTION":{"kind":"string","value":"Product subcat with duplicate name of a subcat of another cat gets the category name in the slug\nSuppose the following categories tree in Woo:\n \n \n Men (slug men)\n -- Shoes (slug shoes / was created first)\n Women\n -- Shoes (slug shoes-women / was created second)\n \n\nWhy is this happening? Both subcats belong to different categories. Why is the category slug appended to the name of the second _duplicate_ subcat?\n\nAnd anyway, for whatever reason Autommatic decided to program it that way, I need to change it, as the nature of the e-shop I'm building is full of such _duplicate_ subcat names, as it will sell clothing, and there will be the same subcat and even subsubcat names for many categories (Men, Women, Kids, etc)...\n\nAny insight on this?"},"RESPONSE":{"kind":"string","value":"It took me two days to figure this out in the proper way, so I'll add it here for anyone else that may need it in the future.\n \n \n add_filter('wp_unique_term_slug', 'prevent_cat_suffix', 10, 3);\n function prevent_cat_suffix($slug, $term, $original_slug)\n {\n if ($term->post_type == 'product' && $term->parent !== 0) {\n return $original_slug;\n }\n \n return $slug;\n }\n \n\nAs you can see in the code, I've narrowed it down to products only, but you can make it suitable for any other post type also by removing the `$term->post_type == 'product' &&` in the code above."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 1,\n \"tags\": \"hierarchical\"\n}"}}},{"rowIdx":6330640,"cells":{"INSTRUCTION":{"kind":"string","value":"Get last published post in Wordpress using wp-cli\nI'm using below `wp-cli` command to get latest post ID:\n\n`wp post list --order='DESC' --orderby='ID' --field='ID' | head -1`\n\nThis, however is inefficient as all posts are retrieved from DB and then `head` limits the number of returned posts.\n\nIs there a way to limit the number of returned posts using wp query?"},"RESPONSE":{"kind":"string","value":"Simply add:\n \n \n --posts_per_page=1\n \n\nto limit the queried items to a single item."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 1,\n \"tags\": \"wp cli\"\n}"}}},{"rowIdx":6330641,"cells":{"INSTRUCTION":{"kind":"string","value":"Block to Popup Page, on demand?\nI have embedded HTML in a block which renders a Python console. What I want to do is to be able to pop-out the Block in a separate window.\n\nIf that is not possible then may be a link that when I click on it pops-up a page that contains the console.\n\nHow do i do that ?\n\n* * *\n\nI don't want the pop-up to be full-screen. I want to be able to move it around, so the text below can be seen.\n\nThe HTML can be anything, I just give it as example. Let say :\n \n \n
    12345
    \n \n\n* * *\n\ni know js/html/css but no idea of how wp works...\n\nDo i just embed html link with onclick=window.open(...) pointing to a wp-page ? Ooo but i have to somehow make it pure page i.e. no theme !! HOW?\n\nAnd second i have to hide ABC !\n\n* * *\n\nGot it : <\n\nhere is working : <\n\ndont look at the site ... it is still under construction ;)"},"RESPONSE":{"kind":"string","value":"Solved it : <\n\nhere is working : <\n\nFirst install the “Blank Slate” plugin. \nCreate New Page \nLeave the Title empty \nSet in Page property Template=”Blank Slate” \nAdd whatever content you want \nBecause there is no Title, we need set a Permalink so that is human readable, let say : your-site/blah \nPublish the page \nGo to the page you want to have the popup window show up on clicking a link \nAdd the following code :\n \n \n Popup window"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"pages\"\n}"}}},{"rowIdx":6330642,"cells":{"INSTRUCTION":{"kind":"string","value":"Custom meta_query order for Elementor based on post meta key\nI'm failing at writing an Elementor `$meta_query` function so posts will be ordered by `meta_value_num` of a given key.\n\nEach post has a numeric value for the key `google_unique_page_views`\n\nMy example is below:\n \n \n // Custom query to order 'recommended reading' posts by populatrity\n add_action( 'elementor/query/my_custom_filter', function( $query ) {\n $meta_query = $query->get( 'meta_query' );\n if ( ! $meta_query ) {\n $meta_query = [];\n }\n $meta_query[] = [\n 'order'=> 'DESC',\n 'key' => 'google_unique_page_views',\n 'orderby' => 'meta_value_num',\n ];\n $query->set( 'meta_query', $meta_query ); \n });\n \n\nDo I need to include the `value` query?"},"RESPONSE":{"kind":"string","value":"Assuming that you want to get posts with that meta key, regardless of content, and order by that meta value, you would need to set two properties.\n\n 1. meta_query\n 2. orderby\n\n\n\nSo the code, based of your question would be like this\n \n \n // Custom query to order 'recommended reading' posts by populatrity\n add_action('elementor/query/my_custom_filter', function ($query) {\n if (empty($meta_query = $query->get('meta_query'))) $meta_query = [];\n \n // add our condition to the meta_query\n $meta_query['google_unique_page_views'] = [\n 'key' => 'google_unique_page_views',\n 'compare' => 'EXISTS',\n ];\n \n // set the new meta_query\n $query->set('meta_query', $meta_query);\n \n // set the new orderby\n $query->set('orderby', [\n 'google_unique_page_views' => 'DESC' // or ASC, based on your needs\n ]);\n });"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 1,\n \"tags\": \"wp query, filters, meta query\"\n}"}}},{"rowIdx":6330643,"cells":{"INSTRUCTION":{"kind":"string","value":"How to get current cart values using WC_Shortcodes?\nI am trying to get current cart items from my own plugin using WC_Shortcodes::cart(); this will return cart details in html format.\n\nWC()->cart->get_cart();\n\ncode not working. i need only cart data without html format. please advise thank you."},"RESPONSE":{"kind":"string","value":"You can get the value by using the global var\n \n \n global $woocommerce;\n \n $cart_value = floatval( preg_replace( '#[^\\d.]#', '', $woocommerce->cart->get_cart_total() ) );\n \n\nOr\n \n \n WC()->cart->total"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"plugins, php, functions, shortcode\"\n}"}}},{"rowIdx":6330644,"cells":{"INSTRUCTION":{"kind":"string","value":"How can I add a UTM tag with PHP code to pick up the post slug dynamically in the UTM?\nThe thing I want to do is doable, but I don't know how to do it.\n\nEmbarrassment moment coming up: I actually did this a few years ago but lost the code and can't find online how it's done.\n\nWhat I want to do is to add a dynamic UTM tag on a link in my header so that the UTM tag picks up the slug of the page the visitor is clicking from.\n\nExample: If the visitor is on a post with the slug /something-goes-here/ and clicks on the CTA button, the CTA page that he goes to should have /second-page/?utm_source=something-goes-here\n\nDo you guys know how this can be done with a bit of code in PHP?"},"RESPONSE":{"kind":"string","value":"What comes to mind is getting the current post by `global $post`, next getting the post slug by `$post->post_name`, next checking the slug if it needs to update a link with a utm query.\n\nSo something like this.\n \n \n // get the current post\n global $post;\n \n // get the post slug, if not set then set it to empty string\n $post_slug = $post->post_name ?? '';\n \n // an array of slugs that need to add utm to link\n $utm_slugs = [\n 'slug-1',\n 'slug-2',\n 'slug-3'\n ];\n \n // set default value (empty string), in case no slug was matched\n $utm_query = '';\n \n // if post slug exists and in the utm slugs array, set a utm query\n if (!empty($post_slug) && in_array($post_slug, $utm_slugs)) $utm_query = '?utm_source=' . $post_slug;\n \n\nNow that we have the php part taken care of we need to create the link. \nThis is just an example so change it accordingly.\n \n \n \">Some link"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"php, google analytics\"\n}"}}},{"rowIdx":6330645,"cells":{"INSTRUCTION":{"kind":"string","value":"Gutenberg custom block using only register_block_type() and HTML\nI have the following core block HTML\n \n \n \n
    \n

    Hello world

    \n \n \n \n

    Lorem ipsum dolor...

    \n
    \n \n \n\nIs it possible to create a custom block from PHP using that HTML? Similar to as I would create Patterns?\n\nregister_block_type() can be used to register blocks from PHP. Is it possible to simply pass the HTML to `register_block_type()` and create the custom block?"},"RESPONSE":{"kind":"string","value":"No, blocks are built with more than HTML - they need JS and PHP.\n\nHowever, you could add an HTML block wherever you need it, then click the More Options dots in the block's toolbar, click Add to Reusable Blocks, name your block, and save it. That block will then be available to use wherever you want it, and if you edit it, that will apply the changes everywhere."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 2,\n \"tags\": \"php, block editor, json\"\n}"}}},{"rowIdx":6330646,"cells":{"INSTRUCTION":{"kind":"string","value":"How to add a CSS class to this php code\nHow can I add a CSS class to \"هر متر طول\" in this php code:\n \n \n add_filter( 'woocommerce_get_price_html', 'themefars_text_after_price' );\n \n function themefars_text_after_price($price){\n \n global $post;\n \n $product_id = $post->ID;\n \n $product_array = array( 1204,1202 );//add in the product IDs to add text after price\n \n if ( in_array( $product_id, $product_array )) {\n \n $text_to_add_after_price = ' هر متر طول '; //change text in bracket to your preferred text \n \n return $price . $text_to_add_after_price;\n \n }else{\n \n return $price; \n }\n \n }"},"RESPONSE":{"kind":"string","value":"I am not sure where this html tags are allowed where this text is going, but maybe something like this:\n \n \n $text_to_add_after_price = ' هر متر طول ';\n \n\nChange myclass to the class you want to use."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"php, css\"\n}"}}},{"rowIdx":6330647,"cells":{"INSTRUCTION":{"kind":"string","value":"How do I use pre_option_{option_name} correctly?\nI am using a filter to decrypt an api_key that is stored with encryption. I have registered the following hook:\n \n \n // Decrypt API key after it is retrieved\n add_filter('pre_option_percify_api_key', array( __CLASS__, 'decrypt_api_key') );\n \n\nThe problem is, I cannot get at the stored value in the callback:\n \n \n public static function decrypt_api_key($encrypted) {\n // $encrypted is empty:\n \n echo($encrypted);\n // ...\n \n\nAm I calling the function correctly? How do I access the stored value of `percify_api_key` within `decrypt_api_key`?"},"RESPONSE":{"kind":"string","value":"The `pre_option_{$option}` hook is used to filter the value of the option **before** it's retrieved. You need to hook after the value is retrieved so you can manipulate it.\n\nIn this case, you can use the `option_{$option}` hook. So your code will look like this:\n \n \n add_filter('option_percify_api_key', array( __CLASS__, 'decrypt_api_key') );\n \n\nFor more info - take a look at the source of the `get_option` function here. Specifically line #225."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"hooks\"\n}"}}},{"rowIdx":6330648,"cells":{"INSTRUCTION":{"kind":"string","value":"Edit the_category (); for a hierarchical display\nFor my wp theme I want to use the categories as tags on my posts. Example: ![enter image description here](\n\nThe problem is that the category in red must always be the parent and in gold the child.\n\nExcept that returns the categories to me in alphabetical order and not in hierarchical order, so sometimes I end up with the child in red and the parent in gold ...\n\nKnowing that I would only use 2 categories per posts so 1 = the parent and 2 = the child\n\nDo you have a solution?"},"RESPONSE":{"kind":"string","value":"You could assign the post only to the child category, and call the function like so:\n \n \n the_category( ' ', 'multiple' );\n \n\nThis will output (notice the whitepsace between the anchor tags):\n \n \n child"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 0,\n \"tags\": \"php, functions, categories, tags, hierarchical\"\n}"}}},{"rowIdx":6330649,"cells":{"INSTRUCTION":{"kind":"string","value":"last_name + first_name orderby with meta_query [solved]\nI have small issue with orderby. I´m looking solution to orderby ASC (lastname + firstname) example:\n\n 1. Selanne Andy\n 2. Selanne Beeny\n 3. Selanne Teemu\n\n\n\nBut now it arrays something like this:\n\n 1. Selanne Beeny\n 2. Selanne Teemu\n 3. Selanne Andy\n\n\n\nHere is code:\n \n \n $order_by_1 = array(\n 'meta_key' => 'last_name',\n 'meta_query' => array(\n array(\n 'key' => 'last_name',\n 'orderby' => 'meta_value',\n 'order' => 'ASC'\n ),\n array(\n 'key' => 'first_name',\n 'orderby' => 'meta_value',\n 'order' => 'ASC'\n ),\n ), \n 'orderby' => 'meta_value',\n 'order' => 'ASC'\n ); \n \n \n \n $usr_1 = get_users($order_by_1);\n \n // Array of stdClass objects.\n foreach ( $usr_1 as $user ) { ....\n \n\nThanks for the help."},"RESPONSE":{"kind":"string","value":"To do this you need to use named meta query clauses according to the official developer docs for `WP_Query`:\n\n> ## ‘orderby’ with multiple ‘meta_key’s\n> \n> If you wish to order by two different pieces of postmeta (for example, City first and State second), you need to combine and link your meta query to your orderby array using ‘named meta queries’. See the example below:\n> \n> \n> 'meta_query' => array(\n> 'relation' => 'AND',\n> 'state_clause' => array(\n> 'key' => 'state',\n> 'value' => 'Wisconsin',\n> ),\n> 'city_clause' => array(\n> 'key' => 'city',\n> 'compare' => 'EXISTS',\n> ), \n> ),\n> 'orderby' => array( \n> 'city_clause' => 'ASC',\n> 'state_clause' => 'DESC',\n> ), ) ); ```\n> \n\n<\n\nThis question was also asked and answered already here:\n\nOrder by multiple meta key and meta value"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"meta query, user meta, array, order, wp user query\"\n}"}}},{"rowIdx":6330650,"cells":{"INSTRUCTION":{"kind":"string","value":"Can you make a custom gutenberg block that allows the gutenberg editor within it?\nI'm looking to achieve basically a wrapper for a collection of gutenberg blocks. The idea is that I can apply some ACF fields to the wrapper and then allow gutenberg to do whatever it does for the inner content.\n\nHowever, I can't add \"gutenberg\" as one of the fields in a custom ACF block. The closest thing I can get is a WYSIWYG editor, so that won't work.\n\nHas anyone here managed to get something like this working? Either a wrapper, or allowing the gutenberg editor to be nested within a custom block?"},"RESPONSE":{"kind":"string","value":"Shucks, no sooner than the second I desperately resort to asking here, I run into the answer. So for anyone else who just wants a straight answer and not some 45 minute video that never gets to the point...\n \n \n acf_register_block_type( array(\n 'title' => __( 'Wrapper', 'client_textdomain' ),\n 'name' => 'wrapper',\n 'render_template' => 'partials/blocks/wrapper.php',\n 'mode' => 'preview',\n 'supports' => [\n 'jsx' => true, // this is the line that makes it work\n ]\n ));\n \n\nThat supports jsx line allows you to assign ACF fields to the wrapper and then the user can gutenberg all they want inside it.\n\nYour custom block's html needs this in it as well:\n \n \n \n \n\nThat will enable the gutenberg interface when adding your block in the editor."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 0,\n \"tags\": \"advanced custom fields, block editor\"\n}"}}},{"rowIdx":6330651,"cells":{"INSTRUCTION":{"kind":"string","value":"Shop page custom buttons which is visible to only administrator\nI created two custom button in woocommerce shop page for every products, and i'm trying to do visible this two buttons only for administrator when he/she login as an administrator.\n\n![enter image description here](\n \n \n add_action( 'woocommerce_after_shop_loop_item', 'product_visibility_button', 5 );\n \n function product_visibility_button() {\n echo '
    ';\n echo 'BTN1';\n echo 'BTN1';\n echo '
    ';\n }"},"RESPONSE":{"kind":"string","value":"you can use the following code to check if a user is logged in and has a valid role.\n \n \n add_action( 'woocommerce_after_shop_loop_item', 'product_visibility_button', 5 );\n function product_visibility_button() {\n \n if ( is_user_logged_in() ) {\n $user = wp_get_current_user();\n if ( in_array( 'administrator', (array) $user->roles ) ) {\n echo '
    ';\n echo 'BTN1';\n echo 'BTN1';\n echo '
    ';\n }\n }\n }"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"customization\"\n}"}}},{"rowIdx":6330652,"cells":{"INSTRUCTION":{"kind":"string","value":"WordPress Gutenberg react make import of __experimentalUseInnerBlocksProps which is no more experimetal\nI have a plugin with import\n \n \n import { __experimentalUseInnerBlocksProps as useInnerBlocksProps } from '@wordpress/block-editor';\n \n\nbut it's not working with newest Gutenberg plugin 11.9, because this `useInnerBlocksProps` is no longer _experimental_\n\nso I can use\n \n \n import { useInnerBlocksProps } from '@wordpress/block-editor';\n \n\nbut then it will not work for older versions, or WordPress installation without Gutenberg plugin.\n\nWhat's the correct way to make it compatible with both scenarios? How to import __experimentalUseInnerBlocksProps if exists and directly useInnerBlocksProps if not?"},"RESPONSE":{"kind":"string","value":"Ok, this is probably the easiest workaround I was able to find, but if someone has better idea, then feel free to post it here ;)\n \n \n import {\n __experimentalUseInnerBlocksProps,\n useInnerBlocksProps,\n } from '@wordpress/block-editor';\n \n if( typeof useInnerBlocksProps == 'undefined' ){\n var compatibleUseInnerBlocksProps = __experimentalUseInnerBlocksProps;\n }else{\n var compatibleUseInnerBlocksProps = useInnerBlocksProps;\n }\n \n\n * so basically I can import both (experimental and no-experimental) without any error\n * then I can just do simple type test if the new one is already supported\n * if it's supported I will remember it in `compatibleUseInnerBlocksProps` variable\n * otherwise I will remember old _experimental_\n * then I need to replace all other occurrences of `useInnerBlocksProps` with `compatibleUseInnerBlocksProps` in my code"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 2,\n \"tags\": \"plugins, plugin development, block editor, import\"\n}"}}},{"rowIdx":6330653,"cells":{"INSTRUCTION":{"kind":"string","value":"How can I get wordpress slug without certain phrase?\nI got this code: `` and I get slug of current post page example: \"dog-training\"\n\nAnd my wordpress posts are like this:\n\ndomain.com/dog-training/ domain.com/dog-toys/ domain.com/dog-food/ etc.\n\nAnd I need to get the slug but only the part \"toys\", \"food\" and \"training\" so I need to get rid of the \"dog-\" part.\n\nWill You help me with this. I`m not a programmer ? Thanks"},"RESPONSE":{"kind":"string","value":"Previous answer here.\n\nYou'll want to use `str_replace`\n \n \n $permalink = get_the_permalink(); \n $permalink = str_replace(\"dog-\", \"\", $permalink);"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"slug\"\n}"}}},{"rowIdx":6330654,"cells":{"INSTRUCTION":{"kind":"string","value":"How can I prevent wordpress from creating tag pages?\nI use the built in wp tag functionality to group my posts thematically and then I use the WP_query to have the posts displayed according to custom design. I do not need the tag pages created by default in wordpress and I would either like to have them NOT created at all (ideally) or be able to add a noindex meta to the post, as these should not be indexed separately. Is there some way to accomplish this?\n\nEDIT: one additional possibility I have looked at is to exclude all matching urls from the sitemap eg exclude all urls matchine /tag/* . I use the Yoast plugin, but I don't see any filter which would allow me to do this type of exclusion."},"RESPONSE":{"kind":"string","value":"To redirect from the automatically-generated tag archive pages, you can check to see if `is_tag()` is true in the `template_redirect` action hook, and redirect with `wp_redirect()` if it is:\n \n \n add_action( 'template_redirect', function() {\n if ( is_tag() ) {\n // Currently redirects to the site's home page.\n wp_redirect( '/' );\n // Use the 301 Permanent redirect if desired.\n // wp_redirect( '/', 301 );\n exit;\n }\n } );\n \n\nTo exclude the tags from the sitemap generated by WordPress (Plan B in your question), you can use the `wp_sitemaps_taxonomies` filter.\n \n \n add_filter( 'wp_sitemaps_taxonomies', function( $taxonomies ) {\n if ( ! empty( $taxonomies['post_tag'] ) ) {\n unset( $taxonomies['post_tag'] );\n }\n return $taxonomies;\n } );"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 1,\n \"tags\": \"tags\"\n}"}}},{"rowIdx":6330655,"cells":{"INSTRUCTION":{"kind":"string","value":"Show popover with url and option to open in new window\nI am creating a custom block and I want to show a button which the user can edit the text of and I want them to be able to select a page/enter a link. I have this working but using `URLInputButton` does not give the option to open in a new tab like the default wordpress popover when you highlight some text and then choose to add a hyperlink.\n\nThis is what I currently have:\n \n \n \n \n\nI have also played around with a popover but not sure how to put what I want in there. This just does what it says and shows text that says 'Popover is toggled!\"\n \n \n "},"RESPONSE":{"kind":"string","value":"There's no support for such a setting in `URLInputButton`/`URLInput` and those components are deprecated. Try `LinkControl`. It may be helpful to study its use in the core Button block. That seems similar to what you are building."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"theme development, block editor\"\n}"}}},{"rowIdx":6330656,"cells":{"INSTRUCTION":{"kind":"string","value":"How to change the date and time in REST API for comments?\n/**\n * Add a Formatted Date to the WordPress REST API JSON Post Object\n *\n */\n add_action('rest_api_init', function() {\n register_rest_field(\n array('comment'),\n 'formatted_date',\n array(\n 'get_callback' => function() {\n return get_the_date();\n },\n 'update_callback' => null,\n 'schema' => null,\n )\n );\n });\n \n\nThis is not working for me. I am constantly getting the following in my JSON:\n \n \n \"formatted_date\":false,\"\n \n\nHow can I show it in a format like: `\"28 November 2021, 15:00\"`?"},"RESPONSE":{"kind":"string","value":"In general I would be careful modifying existing endpoints, but you could try using the object passed into the callback, e.g.:\n \n \n 'get_callback' => function( $object ) {\n return date_i18n( __( 'j. F Y, H:i', 'wpse' ), strtotime( $object['date'] ) );\n },"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"rest api, api, date, date time, wp api\"\n}"}}},{"rowIdx":6330657,"cells":{"INSTRUCTION":{"kind":"string","value":"How to get tags outside of loop for specific page I'm on?\nOutside the loop, if I use the following code in my child theme...\n \n \n $mtags = get_tags(array(\n 'taxonomy' => 'custom_tag',\n 'orderby' => 'name'\n ));\n \n \n\nIt prints out all my tags. But how can I only get tags relating to the page I am viewing?"},"RESPONSE":{"kind":"string","value":"First you need to get the ID of the page/post/content you're viewing. Then, you can call `get_the_terms()` and pass it that ID so it knows you want the tags for that specific piece of content.\n \n \n \n \n\nThere isn't an `orderby` parameter, so you may need to sort the array afterward if you want them in a specific order."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"tags\"\n}"}}},{"rowIdx":6330658,"cells":{"INSTRUCTION":{"kind":"string","value":"GitHub plugins safe to use in my website?\nI have some question about GitHub files, I hope it is a proper place to ask.\n\nI downloaded the gravity forms from <\n\nYou may know that the plugin itself is sold by min price 59$/year in its website <\n\nI am surprised if it is not free in the original website, how it can be downloaded for free at GitHub?\n\nDo you think I can use the version from GitHub without any stability and safety issues?\n\nThanks"},"RESPONSE":{"kind":"string","value":"The GitHub repository changelog is updated until version 2.4.20.\n\nThe official Wordpress is currently updated to version 3.1.25.\n\nSo in answer to your question, you can see that the GitHub repository appears to be abandoned, and therefore it does pose security flaws and you won’t get updates."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"plugins, plugin development, plugin gravity forms, github\"\n}"}}},{"rowIdx":6330659,"cells":{"INSTRUCTION":{"kind":"string","value":"Gutenberg: how to hide server side render output in the editor but keep it in frontend?\nMy goal is to use the Gutenberg Block for the backend editor to collect the data but output it only with php.\n\nI added a server-side-render component to my block. Now I can edit attributes in the Gutenberg Editor and output them on the server side with php. But the output is renderer in the editor as well. I don't need that because it displays everything twice. How do I hide the server side render output in editor?\n\nDo I prevent the output in php with something like \"if is_frontend() {return $output}\" or is there an attribute for server side render to keep it off Gutenberg?"},"RESPONSE":{"kind":"string","value":"This can be down in the php render_function. Check if it is an API REST request:\n \n \n function create_block() {\n register_block_type( __DIR__ ,[\n 'render_callback' => 'render_php'\n ] );\n }\n \n function render_php(){\n \n \n if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {\n return \"

    Backend says hello from php

    \";\n } else {\n return \"

    Frontend says hello from php

    \";\n };\n \n \n }"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 1,\n \"tags\": \"block editor\"\n}"}}},{"rowIdx":6330660,"cells":{"INSTRUCTION":{"kind":"string","value":"Storefront theme : Add Categoy to recent products section\nI want to modify the Recent Products section Storefront theme to be able to include juste a specific category. i tried that :\n \n \n add_filter( 'storefront_recent_products_args', 'my_custom_storefront_category_args' );\n function my_custom_storefront_category_args( $args ){\n $args = array(\n 'limit' => 8,\n 'columns' => 4,\n 'category__in' => array ('35') \n );\n return $args;\n }\n \n\nbut no success"},"RESPONSE":{"kind":"string","value":"I found it , the question is resolved : Solution :\n \n \n add_filter( 'storefront_recent_products_args','my_custom_storefront_category_args' );\n function my_custom_storefront_category_args( $args ){ \n $args = array( \n 'limit' => 6, \n 'columns' => 3, \n 'orderby' => 'date', \n 'order' => 'desc', \n 'category' => 'your-cat-slug', \n 'cat_operator' => 'AND' \n );\n \n return $args; \n }"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"child theme\"\n}"}}},{"rowIdx":6330661,"cells":{"INSTRUCTION":{"kind":"string","value":"Get the URL of the page from which an ajax request has been launched within ajax callback\nI'm calling a server-side function written in PHP via `wp-ajax`. The server-side function eventually redirects to another page for an authentication step, and then redirects back to the initially shown page. For this to work in a generic way, I need to pass the URL from which the AJAX request was fired onto the server-side function. How can I actually do this?\n\nWhen I try for example this, I get the link to `wp-admin/admin-ajax.php`...\n\nI know that I could in theory use `window.href`or whatever in js and send that to the server, but I want to avoid this extra-piece of data sent, as I'm thinking that there must be some built-in wp feature for this...?"},"RESPONSE":{"kind":"string","value":"Ok got it, knew there must be some built-in WP solution to this. Simply call `wp_get_referer()` in your callback (for details, see this).\n\nAt least it's working as I need it, let me know if there's any better solution.\n\n_**UPDATE**_\n\nThanks to @Tom J Nowell, we should also mention that referrers could get stripped for privacy reasons or similar. To thus be on the safe side, there's no way around passing the referrer's URL explicitely to the data sent across AJAX, like using `document.location.href`."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 3,\n \"question_score\": 0,\n \"tags\": \"php, ajax, urls, site url\"\n}"}}},{"rowIdx":6330662,"cells":{"INSTRUCTION":{"kind":"string","value":"Display Ad on Specific Categories\nI want to display the ad only in specific categories. Can anyone help me here's the code to display the ad on all single posts/\n \n \n "},"RESPONSE":{"kind":"string","value":"This will display the ad on all posts belonging to the categories listed in the array:\n \n \n ID ) ) {\n get_template_part( 'template-parts/ads/below-head' );\n } ?>"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 1,\n \"tags\": \"custom post types, posts\"\n}"}}},{"rowIdx":6330663,"cells":{"INSTRUCTION":{"kind":"string","value":"how to create a custom page in child theme or plugin?\ni'm kind of new to plugins .\n\nfor a project we need to create a special form which normal plugin won't help us . we should create a special form page which insert data to db . the main problem is because of limit of modification of main theme i can not directly do changes i want. my question was is there any way to create that custom page template using plugin or child theme ?\n\nevery answers will be welcomed :)"},"RESPONSE":{"kind":"string","value":"you just need to copy a Page Template from the Parent Theme into your Child Theme and rename that template with the new which you want to set into the site or create a new template PHP file add below code:\n \n \n "},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"plugins, child theme\"\n}"}}},{"rowIdx":6330664,"cells":{"INSTRUCTION":{"kind":"string","value":"Redirect when not logged and parametr in link\nhow do I redirect to 'domain.com/sub' for unlogged users, when the url is without the \"one_time_login\" parameter? This should not work when a user is trying to login via sub.domain.com/wp-admin. Have no idea. I understand that htaccess cant make this? Thanks for your help!"},"RESPONSE":{"kind":"string","value":"This should work for what you're looking to achieve;\n \n \n add_action( 'template_redirect', 'redirect_to_specific_page' );\n function redirect_to_specific_page() {\n if ( ! is_user_logged_in() && ! is_page('one_time_login') ) {\n wp_redirect( 'domain.com/sub', 301 ); \n exit;\n }\n }\n \n\nThis should be added to your theme (or child theme) functions.php file"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"redirect\"\n}"}}},{"rowIdx":6330665,"cells":{"INSTRUCTION":{"kind":"string","value":"WooCommerce get_price returning wrong price when used via ajax\nI'm working on a site that uses the Events Tickets plugin, and I need to get the price of a ticket (Woo product) by ID. I'm using `wc_get_product( $ticketID )->get_price();` to to do this.\n\nAdding the price to the page using the code below gives the correct price (e.g. 30):\n \n \n echo 'get_price() . '\">';\n \n\nHowever, when I try and get the price using the same method within an Ajax call it returns 300:\n \n \n function get_ticket_price() {\n $ticketID = $_REQUEST['ticketID'];\n echo wc_get_product( $ticketID )->get_price();\n }\n add_action( 'wp_ajax_get_ticket_price', 'get_ticket_price' );\n add_action( 'wp_ajax_nopriv_get_ticket_price', 'get_ticket_price' );\n \n\nI've also tried using `get_regular_price` but that also returns 300.\n\nAny ideas what's going on here?"},"RESPONSE":{"kind":"string","value":"It's important to exit the function when using the wp_ajax hooks. Hopefully this fixes it.\n \n \n function get_ticket_price() {\n $ticketID = $_REQUEST['ticketID'];\n echo wc_get_product( $ticketID )->get_price();\n \n // Don't forget to stop execution afterward.\n wp_die();\n }\n add_action( 'wp_ajax_get_ticket_price', 'get_ticket_price' );\n add_action( 'wp_ajax_nopriv_get_ticket_price', 'get_ticket_price' );"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 1,\n \"tags\": \"plugins, php, plugin development, theme development, ajax\"\n}"}}},{"rowIdx":6330666,"cells":{"INSTRUCTION":{"kind":"string","value":"Override a function defined in wp-includes/comment-template.php\nI need to override the function `get_cancel_comment_reply_link` or `cancel_comment_reply_link` that are defined in\n \n \n wp-includes/comment-template.php\n \n\nThese functions are not listed in `pluggable.php`.\n\n**How can I override them from my theme's`functions.php`?**\n\nI tried\n \n \n remove_filter('get_cancel_comment_reply_link', 'cancel_comment_reply_link');\n add_filter('get_cancel_comment_reply_link', function($text='') { return ''; }, 1, 1);\n \n\nwithout success."},"RESPONSE":{"kind":"string","value":"If you look at the end of the function `get_cancel_comment_reply_link( $text = '' )` in the file `wp-includes/comment-template.php`, you see the filter `cancel_comment_reply_link`.\n \n \n return apply_filters( 'cancel_comment_reply_link', $formatted_link, $link, $text );\n \n\nIt may work."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 0,\n \"tags\": \"php, functions, filters, actions, pluggable\"\n}"}}},{"rowIdx":6330667,"cells":{"INSTRUCTION":{"kind":"string","value":"get_the_ID() in the footer returns wrong value\nI'm using `get_the_ID()` in `footer.php` but it returns a wrong value.\n\nIt might come from any of the plugin which is altering The Loop without resetting it after with `wp_reset_postdata()` as mentioned in $post->ID and the_id() always return the wrong value.\n\nIndeed the page shows a list of recent posts, etc. so this might modify the current Loop.\n\nIf I can't modify this (because of third party code), how to **get the ID of the current post** in the footer anyway, with PHP?"},"RESPONSE":{"kind":"string","value":"In an environment without third party code, `get_the_ID()` should give you the correct value. It sounds like some plugin is interfering with this.\n\nSo you can do what they forgot and simply call\n \n \n wp_reset_postdata()\n \n\nin your footer before you need the values."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"php, wp query, loop, id, get the id\"\n}"}}},{"rowIdx":6330668,"cells":{"INSTRUCTION":{"kind":"string","value":"How to make content area in full width in Twenty Twenty-One theme?\nI've a child Twenty Twenty-One theme and I want to make the content area in full with. I don't want to use any plugin. I've searched and found that adding following code in CSS may work but for me it's not working.\n\nHow to do it with css if it is possible?\n \n \n .entry-content > \n *:not(.alignwide):not(.alignfull):not(.alignleft):not(.alignright):not(.is-style-wide) {\n max-width: 87rem;\n width: calc(100% - 8rem);\n }"},"RESPONSE":{"kind":"string","value":"I figured it out. It is the inherit default layout settings. First turn that off and then enter the desired width."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"themes, theme twenty twelve\"\n}"}}},{"rowIdx":6330669,"cells":{"INSTRUCTION":{"kind":"string","value":"How to prevent sending auto emails for specific actions in wordpress\nHow to prevent sending auto emails for specific actions in wordpress, i have a function that generate password for users, only after the admin accept the user application\n \n \n create_user_password($subscription->ID),\n //this function calls wp_update_user\n \n\nWordpress sends a message about a (password change action), how to prevent this ONLY if this method was triggered by an admin"},"RESPONSE":{"kind":"string","value":"If you look in the documentation of `wp_update_user()` you will see that it uses two filters:\n\n * `send_password_change_email`\n * `send_email_change_email`\n\n\n\nSimply from the names I would guess if you return `false` in `send_password_change_email` it should work. So something along the lines of:\n \n \n function create_user_password($id) {\n // other code\n add_filter('send_password_change_email', '__return_false');\n wp_update_user(...);\n remove_filter('send_password_change_email', '__return_false');\n }"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"email\"\n}"}}},{"rowIdx":6330670,"cells":{"INSTRUCTION":{"kind":"string","value":"Get posts for which a custom field is not present, with get_posts\nI'd like to get all posts for which the custom field `hidden` is NOT present. This does not work:\n \n \n $postsForSitemap = get_posts(array(\n 'numberposts' => -1, \n 'orderby' => 'modified', \n 'post_type' => array('post', 'page'), \n 'order' => 'DESC', \n 'meta_key' => 'hidden', \n 'meta_compare' => '!=')\n );\n \n\nbecause `meta_compare` is about the `meta_value`, not the key.\n\nI haven't found in the documentation < how to get all posts that _don't have_ a specific custom field.\n\nHow to do this?"},"RESPONSE":{"kind":"string","value":"You could use `NOT EXISTS` as the value for comparem, you could also check for empty value if thats relevant\n\nThis code only checks if `hidden` meta does not exists\n \n \n $postsForSitemap = get_posts([\n 'numberposts' => -1, \n 'orderby' => 'modified', \n 'post_type' => ['post', 'page'], \n 'order' => 'DESC', \n 'meta_key' => 'hidden', \n 'meta_compare' => 'NOT EXISTS'\n ];\n \n\nThis checks is `hidden` meta does not exists OR has no value\n \n \n $postsForSitemap = get_posts([\n 'numberposts' => -1, \n 'orderby' => 'modified', \n 'post_type' => ['post', 'page'], \n 'order' => 'DESC', \n 'meta_query' => [\n 'relation' => 'OR',\n [\n 'key' => 'hidden',\n 'compare' => 'NOT EXISTS',\n ],\n [\n 'key' => 'hidden',\n 'value' => ''\n ]\n ]\n ];"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 1,\n \"tags\": \"wp query, custom field, get posts\"\n}"}}},{"rowIdx":6330671,"cells":{"INSTRUCTION":{"kind":"string","value":"Converting Y-m-d to a date with a Month name?\nSo I can easily get today's date with:\n \n \n echo (date(\"Y-m-d\"));\n \n\nThe above outputs: 2021-12-06\n\nHow do I get 2021 December 06 from the above format?\n\nP.S. I will be storing 2021-12-06 into my database. Later I will want to convert this format into the example I gave above.\n\nThanks for your help."},"RESPONSE":{"kind":"string","value":"You can use createFromFormat to re-format your date. Like so:\n \n \n $date = DateTime::createFromFormat('Y-m-d', '2021-12-06');\n echo $date->format('Y F d');\n \n\nIf you want your output to be anything other than \"2021 December 06\", please check PHP datetime formats for all available formatting options."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 0,\n \"tags\": \"php, date\"\n}"}}},{"rowIdx":6330672,"cells":{"INSTRUCTION":{"kind":"string","value":"How do I attach a page to a category similar to how we attach media to a post?\nIs it possible/how do I to attach a page to a category similar to how we attach media to a post?\n\nps. I'm not asking how to assign a category to a page.\n\nupdate: I need to attach a specific page contents on top of the archive of a specific category archive."},"RESPONSE":{"kind":"string","value":"No, media is attached to posts/pages using the `post_parent` column. This works because media is actually a post of type `attachment` in the database.\n\nCategories however are not posts, and the way you would attach them is by assigning the page to that category.\n\nThis leads us to a contradiction, how do you attach a page to a category without attaching it to a category?\n\nI'm sure that your original problem is solvable but this is not the solution."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"categories, pages\"\n}"}}},{"rowIdx":6330673,"cells":{"INSTRUCTION":{"kind":"string","value":"how to add display_name from the users table to this query\nhow to add display_name from wordpress users table to this query thanks for the help\n \n \n SELECT a.post_title, b.meta_key, b.meta_value as level, c.meta_value as intro\n FROM wp_posts a\n LEFT JOIN wp_postmeta b ON a.ID = b.post_id\n LEFT JOIN wp_postmeta c ON a.ID = c.post_id\n WHERE b.meta_key = 'level'\n AND c.meta_key = '_post_main_intro'"},"RESPONSE":{"kind":"string","value":"You should be able to do something like this, by adding in another join, and selecting the `display_name` column from that joined table:\n \n \n SELECT a.post_title, b.meta_key, b.meta_value as level, c.meta_value as intro, u.display_name\n FROM wp_posts a\n LEFT JOIN wp_postmeta b ON a.ID = b.post_id\n LEFT JOIN wp_postmeta c ON a.ID = c.post_id\n LEFT JOIN wp_users u ON a.post_author = u.ID\n WHERE b.meta_key = 'level'\n AND c.meta_key = '_post_main_intro'\n \n\nHopefully this works for you!"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"php\"\n}"}}},{"rowIdx":6330674,"cells":{"INSTRUCTION":{"kind":"string","value":"How to display tags with post_content\nI have this code to display the content of a specific post outside the loop (actually in the archive.php template file). How do I include the tags?\n \n \n post_content;\n $content = apply_filters('the_content', $content);\n $content = str_replace(']]>', ']]>', $content);\n echo $content;\n ?>"},"RESPONSE":{"kind":"string","value":"Simply use `get_the_tags($my_id)`, example :\n \n \n $posttags = get_the_tags($my_id);\n if ($posttags) {\n foreach($posttags as $tag) {\n echo $tag->name . ' '; \n }\n }\n \n\nRefering to WordPress codex"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"tags, post content\"\n}"}}},{"rowIdx":6330675,"cells":{"INSTRUCTION":{"kind":"string","value":"Use PHP code to create custom user roles. Call it once?\nI have the following PHP code in my wordpress site. I have noticed that when I disable the following code, those two user roles still exists both for current and new users.\n \n \n /* ------------------------------ ADD NEW CUSTOM ROLES ------------------------------ */\n add_role('barber',_('Barber'),array('read' => true, 'edit_posts' => true));\n add_role('barber_shop',_('Barber Shop'),array('read' => true, 'edit_posts' => true));\n /* ---------------------------------------------------------------------------------- */\n \n\nMy question is, do I need to call this code once, or should I always keep it running? Will it cause any issue in the future?"},"RESPONSE":{"kind":"string","value":"Generally, you would call this code in a plugin activation hook or at the very least, `init`. The issue you _may_ run into is calling this code too early if it's outside any specific WordPress hooks which would cause issues. That being said, `add_role()` calls `WP_Roles::add_role()` and one of the first things it does is check if it's already defined via:\n \n \n if( empty( $role ) || isset( $this->roles[ $role ] ) ) {\n return;\n }\n \n\nWordPress saves roles in the options table and grabs those roles on instantiation. If the role is already set, it's just going to return early no harm, no foul."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"user roles\"\n}"}}},{"rowIdx":6330676,"cells":{"INSTRUCTION":{"kind":"string","value":"How to use category slug to echo a page's content with the same slug\nHow can I fit this category slug\n\n`slug; ?>`\n\ninto this page content ` 'slug-goes-here', 'post_type' => 'page' ]); if ( $page ){ echo $page[0]->post_content;} ?>`"},"RESPONSE":{"kind":"string","value":"Worked it out...\n \n \n \n $term->slug,\n 'post_type' => 'page'\n ]);\n if ( $page ){ echo $page[0]->post_content; } \n ?>"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"terms\"\n}"}}},{"rowIdx":6330677,"cells":{"INSTRUCTION":{"kind":"string","value":"Display logged in user name and lastname on page\nI want to display the first an lastname of my users on a welcome site. I have some code in my functions.php that let me show the first name. How can I change the code to show both first and last?\n\nThis is my code for the shortcode:\n \n \n function custom_shortcode_func() {\n ob_start();\n $current_user = wp_get_current_user();\n echo 'Willkommen ' . $current_user->user_firstname . '
    ';\n $output = ob_get_clean();\n return $output;\n }\n add_shortcode('current_user', 'custom_shortcode_func');"},"RESPONSE":{"kind":"string","value":"You can always do a `var_dump()` of `$current_user` to see what it contains. You'll see there is a similar property to `user_firstname`: `user_lastname`.\n\nYou'll probably want a space between the first and last name, so a small edit should add the last name:\n \n \n function custom_shortcode_func() {\n ob_start();\n $current_user = wp_get_current_user();\n echo 'Willkommen ' . $current_user->user_firstname . ' ' . $current_user->user_lastname . '
    ';\n $output = ob_get_clean();\n return $output;\n }\n add_shortcode('current_user', 'custom_shortcode_func');\n \n\nAs you can see you're already getting the last name and other data, so the tweak just adds a space character and the last name."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"php, functions, shortcode\"\n}"}}},{"rowIdx":6330678,"cells":{"INSTRUCTION":{"kind":"string","value":"Live Streaming with Wordpress?\nDoes anyone know a working set up for a live streaming event delivered by a wordpress page? There should be 500 participants. I have no idea, what I need to consider and which technological set up neccessary to do this. YouTube / Zoom is not an option, because the event should be delivered on an excklusive page with restricted accesss …\n\nBest and thank you."},"RESPONSE":{"kind":"string","value":"You can use Jitsi, it’s open source and can be embedded/integrated as you require for member areas etc. Here’s an example plugin that uses it.\n\nI have no affiliation with Jitsi or the plugin."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"plugins\"\n}"}}},{"rowIdx":6330679,"cells":{"INSTRUCTION":{"kind":"string","value":"Add wordpress to only one domain in shared hosting with multiple domains\nI got a shared hosting plan with namecheap in which I'm hosting multiple domains. I want to use only one of this domains with wordpress. Can I just install Softaculous Wordpress on my cPanel with any worries. If yes, how can link the domain I want to wordpress? Will the other domains be affected by wordpress installation?"},"RESPONSE":{"kind":"string","value":"so from my experience as a WordPress developer, the only downside of the shared hosting is that that's all you got ( in terms of memory ). so if you install Wordpress from the official site and then upload it to the correct path ( let's say you have bought 3 domains: marinario.ko, marinario.com, marinario.it and the primary domain is marinario.com then inside public_html you can upload the zip of WordPress, if you want to create with WordPress one of the other domain then you have to upload it to public_html/marinario.ko lets say. then you can unzip it and move all the files directly to the folder. then you have to create a DB with a user. you can go then to marinario.com ( if you have uploaded it to public_html ) and enter all the data it wants. if you have any problem with hhtps you can add a redirect rule inside cPanel. I hope I have helped you :)"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"hosting, shared hosting\"\n}"}}},{"rowIdx":6330680,"cells":{"INSTRUCTION":{"kind":"string","value":"Does the WordPress core software handle bounces on system email?\nThe WordPress core sends a number of system emails, such as for password changes and for form plugins that use the WordPress core. If any of those emails bounce, does the WordPress core receive and handle them?"},"RESPONSE":{"kind":"string","value":"The quick answer: no. At least not out of the box.\n\nThe bouncing email goes to the mail server and if there is no mailbox, catch-all or redirect address set, it will just bounce. You would need to connect WordPress to via pop3 or IMAP to receive emails.\n\nThere is at least one plugin for using WordPress as a mail client. I am not sure how it works, so I don't know secure it is and how it (potentially) impacts WordPress performance."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 0,\n \"tags\": \"email\"\n}"}}},{"rowIdx":6330681,"cells":{"INSTRUCTION":{"kind":"string","value":"is $wpdb->get_results() safe enough\n#### original question\n\nif I use the get_results() functions is this safe enough from mysql injection attacks?\n \n \n global $wpdb;\n $wpdb->get_results(\"select * from tableA where B = C\");\n \n\nOr should this have some kind of prepare first? What's the best practice? How should we do it in our present time December 2021 ?\n\n#### update\n\nso I should use this instead?\n \n \n global $wpdb;\n $my_variable = \"sometext\";\n $prep = $wpdb->prepare(\"select * from tableA where B = %s\", $my_variable);\n $wpdb->query($prep);"},"RESPONSE":{"kind":"string","value":"You have to always use $wpdb->prepare() before $wpdb->query() or $wpdb->get_results() if your queries depend on dynamic variables"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 4,\n \"question_score\": 0,\n \"tags\": \"database\"\n}"}}},{"rowIdx":6330682,"cells":{"INSTRUCTION":{"kind":"string","value":"How to limit the number of images displayed in the media window?\nI have a lot of images in my website, so when I open `wp-admin/upload.php` the server slow down. Would be possible to display only 50 images per time?\n\nI saw there is this similar question, but it works only for the \"set featured image\" popup.\n\nI would like to apply the limit also to the `upload.php` window.\n\nHow can I achieve that?\n\nKind regards"},"RESPONSE":{"kind":"string","value":"maybe this other similar question (with a good answer) can help you. Change default screen option value for media items per page (in media library)\n\nAnd the filter to use is :\n \n \n function my_edit_media_per_page(){\n $media_per_page = 200; //or whatever you want\n return $media_per_page;\n }\n \n add_filter( 'upload_per_page', 'my_edit_media_per_page', 10, 3 );"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 0,\n \"tags\": \"images, uploads, media library\"\n}"}}},{"rowIdx":6330683,"cells":{"INSTRUCTION":{"kind":"string","value":"Using WP_Mail on MacOS 12 (Monterey - M1)\nOn a brand new Macbook running Monterey (M1), as PHP was removed by Apple on OS 12, I have removed all \"AMP\" preinstalled by Apple and installed HomeBrew \"AMP\" (with PHP 7.4), which is running perfectly.\n\nNow, as I have setup Wordpress for testing purposes, I am attempting to use Wordpress WP_Mail function, which relies on PHPMailer, which in turn uses PHP Mail command. The latter relies on system specific libraries, and I am bit confused about configuring the correct facility, Mail, SendMail, Mailsend....\n\nDigging the Internet, once upon a time you would achieve this through Postfix or eventually setting up an email account in the System settings for Mail.app , which I would like to avoid, as I only use web mail on browser and hate to have an email client accessing my account.........\n\nIn conclusion, on a Monterey M1 machine, Homebrew \"AMP\" scenario, is there a way to allow PHPMailer to work, avoiding using Mail.app account?"},"RESPONSE":{"kind":"string","value":"Hi I put this function on the functions.php or in a plugin and works for me everywhere, on localhost or in any server. just need to change the strings to your email smtp settings. Only with gmail I could not make it work so far, all the other ones I try it works perfectly.\n \n \n // Overriding wp smtp email to send smtp emails (no spam emails)\n if (! function_exists('email_sender')){\n add_action('phpmailer_init','email_sender');\n function email_sender($mail){\n $mail->SetFrom('myemail@hotmail.org', 'thenameIwant to appear on the emails sended');\n $mail->Host = 'smtp-mail.outlook.com';\n $mail->Port = 587;\n $mail->SMTPAuth = true;\n $mail->SMTPSecure = 'STARTTLS';\n $mail->Username = 'myemail@hotmail.org';\n $mail->Password = 'mypassword';\n $mail->IsSMTP();\n }\n }\n \n\nthen email should work like a charm! I normally use `wp_mail()` to do it."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 3,\n \"question_score\": 0,\n \"tags\": \"wp mail, smtp\"\n}"}}},{"rowIdx":6330684,"cells":{"INSTRUCTION":{"kind":"string","value":"Automatic translation with different domains per languages?\nI would like to know if there is a plugin to make automatic translations with one different domain by language for the same project. For example :\n\ncar.co.uk for the English\n\nvoiture.fr for the French\n\ncoche.es for the Spanish\n\netc.\n\nAnd still have an automatic translation : If I create a new article in French on voiture.fr, there also an automatic creation and translation on the English version (car.co.uk) and on the Spanish version (coche.es) without any human actions?\n\nI know I can’t do this with Weglot (only one domain) so I’m searching an alternative…\n\nThanks a lot for your answers!"},"RESPONSE":{"kind":"string","value":"I believe you can do this with WPML. Keep in mind that it's a paid add-on and I have not tested it myself. Check out their page here: <"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"translation\"\n}"}}},{"rowIdx":6330685,"cells":{"INSTRUCTION":{"kind":"string","value":"How do I activate my child theme, as I do not see it in developer tools\nI uploaded a child theme from Astra, but the css or javascript does not display, but I was told to look if it is activated. I have looked in developer tools, and I do not see anything about a child theme there. Would anybody know, how I could activate it, if that is the problem. Thanks"},"RESPONSE":{"kind":"string","value":"You can generate your Astra child theme from here.\n\n<"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": -1,\n \"tags\": \"plugins, child theme\"\n}"}}},{"rowIdx":6330686,"cells":{"INSTRUCTION":{"kind":"string","value":"If you have multiple dynamic blocks with a post loop on a page, how do you avoid duplicates from inside the render_callback function?\nI'm building dynamic blocks to customize the blog index into more of a magazine style layout, featured posts, categories, other content, all mixed together. My dynamic blocks are able to render a loop and post content just fine, but I cannot pass a list of IDs from the render_callback block function to itself when it displays multiple times on the same page, leading to duplicate posts in this block when used in various places on a page.\n\nIf you have multiple dynamic blocks rendering a get_posts loop, how do you pass a list of IDs to the next instance to avoid duplicates?"},"RESPONSE":{"kind":"string","value":"In PHP I recall these ways\n\n 1. Static variables\n 2. Class properties\n 3. Databases, Files, Memory (might be flushed though)\n\n\n\nto preserve a state, in a hook's callback, that is called multiple times in WordPress and in the order I would consider using myself but it depends on the context (eg WP transients, that store data that expires, can use memory for speedy recalling and database as a fallback).\n\nGlobal variables might also be listed at the bottom (usually not recommended) and closure tricks closer to the top."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"block editor\"\n}"}}},{"rowIdx":6330687,"cells":{"INSTRUCTION":{"kind":"string","value":"Disable lazy loading on specific images\nWordpress adds lazy loading on all images. Lighthouse recommends disabling lazy loading on images in above the folder. I would like to figure out how to disable it only on images that I call with wp_get_attachment_image_src in my templates, so that I can control exactly which LCP images to remove lazy load.\n\nLighthouse documentation: "},"RESPONSE":{"kind":"string","value":"You can manage WordPress lazy loading with the `loading` parameter. Below code echo's your image without using the lazy load function.\n \n \n echo wp_get_attachment_image( $image, $size, false, [\n 'class' => 'your-class-here', \n 'loading' => 'eager'\n ] );"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 6,\n \"question_score\": 0,\n \"tags\": \"images, performance\"\n}"}}},{"rowIdx":6330688,"cells":{"INSTRUCTION":{"kind":"string","value":"splitting the URL using jQuery\n**Can i get the help of you guys as i want i can do it with url**\n\nI need to split the URL. and use last element as job_id, And then pass \"jkdbsbd45JubJKAAASSYT\" as job_Id.\n \n \n URL: \n \n\nNeed to create this URL as below.\n \n \n Need: \n \n\n**Thanx in advance**"},"RESPONSE":{"kind":"string","value":"Not really a WordPress related question but you could do this\n \n \n // creates a object from the array, one of the properies (search) contains the query\n let url = new URL('\n // will create a object of all availalble query properites\n const urlSearchParams = new URLSearchParams(url.search);\n const params = Object.fromEntries(urlSearchParams.entries());\n // remove ? and everything after from url\n url = url.href.substring(0, url.href.indexOf('?'));\n \n // url + params.job_id is the final url, did a console.log so you could see it in the devtools console\n console.log(url + params.job_id);"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 1,\n \"tags\": \"ajax, javascript, jquery, jquery ui\"\n}"}}},{"rowIdx":6330689,"cells":{"INSTRUCTION":{"kind":"string","value":"Trying to run Javascript on AJAX call\nI am trying to change the classes for the \"View cart\" button after adding an item to the cart. What I tried to do is to hook into the \"woocommerce_ajax_added_to_cart\" action and insert my Javascript as below but this Breaks the AJAX call. I honestly don't know if I am using the correct hook:\n \n \n function set_button_classes() {\n \n echo \"\";\n \n }\n add_action( 'woocommerce_ajax_added_to_cart', 'set_button_classes', 10, 1 ); \n \n\nAny pointers would be really appreciated."},"RESPONSE":{"kind":"string","value":"Found an answer on here. It does work but I am having timing issues I think. They are unrelated to the question though so I will mark the below as the answer. Thanks all.\n \n \n add_action( 'wp_footer', 'trigger_for_ajax_add_to_cart' );\n function trigger_for_ajax_add_to_cart() {\n ?>\n \n {\n console.log( store.getState().lastAction ); // which store?\n } );\n \n\nIs this the correct way or is there something easier?"},"RESPONSE":{"kind":"string","value":"Maybe you will find this snippet helpful. I'm still searching for a better way to do this but as far as I can tell blocks are not aware of their own deletion. Instead we have to monitor the blocks from above. If you have a parent block type that has children, you can subscribe to core/block-editor and use getBlocks() to check the length of children and if the new length is lower than the old length then you have caught a deletion.\n \n \n const getBlockList = () => wp.data.select( 'core/block-editor' ).getBlocks();\n \n let blockList = getBlockList();\n \n wp.data.subscribe( () => {\n \n const newBlockList = getBlockList();\n \n if ( newBlockList.length < blockList.length ) {\n console.log( 'A block was removed!!' );\n }\n \n blockList = newBlockList;\n \n } );"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"block editor\"\n}"}}},{"rowIdx":6330691,"cells":{"INSTRUCTION":{"kind":"string","value":"How to change the link address from internal to external\nLook at the line below It now reads the file (script.js) from the same folder\n\nI want to replace the link to another site for example: `\n \n \n wp_register_script(\n 'post_publisher_js', \n plugins_url('script.js', __FILE__),\n array( 'jquery' ),\n \"1.0.2\"\n );"},"RESPONSE":{"kind":"string","value":"Just replace `plugins_url('script.js', __FILE__)` with `'"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"javascript\"\n}"}}},{"rowIdx":6330692,"cells":{"INSTRUCTION":{"kind":"string","value":"I have a snippet to redirect all users to a maintenance page. How do I exclude users with admin role?\nI have a snippet that redirects all users to a maintenance page. How can I tweak it to All users except admin users?\n \n \n \n RewriteCond %{QUERY_STRING} !^$\n RewriteCond %{QUERY_STRING} !(^|&)appId=\n RewriteCond %{QUERY_STRING} !(^|&)q=\n RewriteRule ^(.+?)\\.html$ [L,R=301]\n \n \n\nThe problem would be solved if this `RewriteCond %{QUERY_STRING} !^$` replace with this `RewriteCond %{THE_REQUEST} \\?`\n\nBut this directive does **not work** on the Litespeed server. That's for sure, I contacted the developers of this server.\n\nHow to cut (redirect) to a link without a question mark **via** function.php?\n\nexample: if open **website.com/post-name.html?** >>>redirect>>> **website.com/post-name.html**\n\nSorry for my English."},"RESPONSE":{"kind":"string","value":"Try this, which uses the `parse_request` hook: (you can add other conditions, e.g. check whether `$wp->query_vars['name']` is not empty, if you want to)\n \n \n add_action( 'parse_request', 'wpse_400900_parse_request', 1 );\n function wpse_400900_parse_request( $wp ) {\n // Redirect if the URL ends with a ? like \n if ( ! empty( $_SERVER['REQUEST_URI'] ) &&\n ltrim( $_SERVER['REQUEST_URI'], '/' ) === \"{$wp->request}?\"\n ) {\n wp_redirect( home_url( $wp->request ) );\n exit;\n }\n }"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 1,\n \"question_score\": 0,\n \"tags\": \"functions\"\n}"}}},{"rowIdx":6330696,"cells":{"INSTRUCTION":{"kind":"string","value":"Edit post & page option does not display on latest wordpress\nI am not able to edit the WordPress default posts/pages from front-end. I have tried to deactivate all plugins, check/uncheck toolbar option(from profile) and also wp_footer() function in the file.\n\nBut no luck any suggestion?"},"RESPONSE":{"kind":"string","value":"I have found the issue and resolved with below code.\n \n \n function menu_shapespace_node_landearth($wp_admin_bar) {\n $wp_admin_bar->remove_menu('edit');\n }\n //add_action('admin_bar_menu', 'menu_shapespace_node_landearth', 999);"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"posts, themes, pages, wp admin, links\"\n}"}}},{"rowIdx":6330697,"cells":{"INSTRUCTION":{"kind":"string","value":"If Post Published Date or Modified Date is 1 Year or Older, Display Notice on Post Page\nI need a way to inform visitors if the post published date **or** modified date is older than 1 year and if so, display a message on the post page.\n\nI have added an code to my `content-single.php` file, but without the desired results in terms of checking against both published and updated time.\n\n**Example:**\n \n \n if (strtotime($post->post_date) < strtotime('-1 year')){\n echo 'Old Post';\n } else {\n echo 'Not Old Post';\n }\n \n\nAny ideas as I'm in the dark here.."},"RESPONSE":{"kind":"string","value":"Right now you're just checking for the post date. You'll need to check for 'post_modified' aswell. You can find the complete post-object here: <\n\nYou can modify the check to look something like this:\n \n \n if (strtotime($post->post_date) < strtotime('-1 year') && strtorime($post->post_modified) < strtotime('-1 year')){\n echo 'Old Post';\n } else {\n echo 'Not Old Post';\n }\n \n\nThat should check for both."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"php, posts, date, date time\"\n}"}}},{"rowIdx":6330698,"cells":{"INSTRUCTION":{"kind":"string","value":"How to rename custom table name programatically in wordpress?\nin db there are custom table name like wp_wpdf_docs and want to change table name to wp_ccdm_docs\n\nas i am using\n \n \n $oldtable_name = $wpdb->prefix . \"wpfd_docs\"; \n \n $newtable_name = $wpdb->prefix . \"ccdm_docs\"; \n \n $rename= $wpdb->query(\"RENAME TABLE \".$oldtable_name .\" TO \" .$newtable_name); \n \n\nis it right process?"},"RESPONSE":{"kind":"string","value":"Yes, you can use the `query` function to rename tables.\n \n \n global $wpdb;\n $oldTable = $wpdb->prefix . \"wpfd_docs\";\n $newTable = $wpdb->prefix . \"ccdm_docs\"; \n $renameOk = $wpdb->query(\"RENAME TABLE \" . $oldTable . \" TO \" . $newTable);\n if( $renameOk )\n {\n echo 'All good';\n }else{\n echo 'Failed to rename table. Last DB error: ' . $wpdb->last_error;\n }"},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 0,\n \"question_score\": 0,\n \"tags\": \"database\"\n}"}}},{"rowIdx":6330699,"cells":{"INSTRUCTION":{"kind":"string","value":"read excel file in the dasboard programmatically\nTo read a excel file inside wordpress, is there any function available, or we should build all using php?"},"RESPONSE":{"kind":"string","value":"> To read a excel file inside wordpress, is there any function available\n\nWordPress does not provide functions for reading spreadsheets. PHP provides functions for reading CSV files via `fgetcsv` etc, but these are for `.csv` files.\n\nIf you want to open an `xls` or `xlsx` file in code, and read its contents, you will need to find a PHP library for this, or implement the code yourself. A quick search of libraries on packagist reveals multiple pages of results for the word \"excel\".\n\nKeep in mind that what you are asking if not a WordPress question, but a generic PHP question, you don't have to limit yourself to just WordPress to solve this."},"SOURCE":{"kind":"string","value":"stackexchange-wordpress"},"METADATA":{"kind":"string","value":"{\n \"answer_score\": 2,\n \"question_score\": 0,\n \"tags\": \"dashboard\"\n}"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":63306,"numItemsPerPage":100,"numTotalItems":6331083,"offset":6330600,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjM3ODA2NSwic3ViIjoiL2RhdGFzZXRzL2RvbmZ1L29hLXN0YWNrZXhjaGFuZ2UiLCJleHAiOjE3NTYzODE2NjUsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.aRnWRh4LJbEr8um1Z_Szs_9D69BykMJBU3tat5CeXQFSXjiQYEDeHdBmcgBm7M2sDCHZpPdZobPcVXQibpwQDg","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
    INSTRUCTION
    stringlengths
    11
    999
    RESPONSE
    stringlengths
    0
    999
    SOURCE
    stringlengths
    16
    38
    METADATA
    dict
    Display all subcategories from parent category I have 20 subcategories from a parent category, and they are like that Parent * September * November * … up to 20 Here is the code that try it to display, but I get only 1 category instead <?php $categories = get_categories('child_of=505'); foreach($categories as $category): ?> <div class="qitem"> <a href="<?php get_category_link( $category->term_id ); ?>" title="<?php echo $category->name; ?>"> <?php echo $category->name; ?> </a> <h4> <span class="caption"> <?php echo $category->name; ?> </span> </h4> <p> <span class="caption"> <?php echo $category->description; ?> </span> </p> </div> <?php endforeach; ?>
    `get_categories()` uses `get_terms()` so the array argument you can pass it will be the same. From the documentation the array can have a property `hide_empty`, by default its `true`. I'm guessing that those categories have no posts attached to it, if that is the case you will need to set it to `false`. The code would be like this. get_categories([ 'child_of' => 505, 'hide_empty' => false ]); ## Update If you want to order the results you can add `order` to the array, the default value is `ASC` so you will need to set it to `DESC`. get_categories([ 'child_of' => 505, 'hide_empty' => false, 'order' => 'DESC' ]); You can check WP_Term_Query::__construct( string|array $query = '' ) for all the available arguments you can use.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "categories" }
    How to get a page slug in WordPress? I would like to know if anyone knows how I can get the call to a wordpress slug with a wordpress function. All this in order that everything is added automatically in the following way, EXAMPLE: <link rel = "alternate" hreflang = "fr-BE" href = " HERE}}" /> As you can see, I only need the function to take the slug of the page without including directories or anything like that. Thanks for your support!
    Going by your link tag and the place you want the slug in, the code would be like this. <link rel="alternate" hreflang="fr-BE" href=" get_post_field('post_name'); ?>" /> You don't need to add all those spaces in attributes, for example, instead of `rel = "alternate"` do `rel="alternate"`, and so on.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "slug" }
    SQL Query to Update Admin Email After pushing a staging site to production I have `[email protected]` set as the admin email which I need to change. Obviously I can't access that email to verify the change because it doesn't exist so I wrote this query: UPDATE wp_options SET option_value = '[email protected]' WHERE option_name = 'admin_email' I found this related answer but I do not use phpMyAdmin. Is this an OK method to override this? Or is there a more proper method?
    While your SQL query will probably do the trick, you don't need to interface directly with the database to accomplish this. The preferred methods would by using Wordpress' `update_option()` function or by running the WP-CLI command:`wp option update`. ## Via `update_option()` To override the admin email change confirmation process, add the following to your `functions.php` file and hit "save changes". `update_option( 'admin_email', '[email protected]' );` Then once you've verified that the change worked, you can go back to your `functions.php` and remove the snippet. * * * ## Via WP-CLI If you have WP-CLI installed, you can run the following command from your shell/terminal (much faster): `wp option update admin_email [email protected]` If WP-CLI is owned by root, you'll obviously need to run it with `sudo`. Success will give you the following output: `Success: Updated 'admin_email' option.`
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 1, "tags": "database, admin, email verification" }
    Looking for a better way to initiate cron job Is there any other good way to initiate an hourly cron job other than using `register_activation_hook` within a plugin? As looks like it will not be useful for websites that have already installed and activated that plugin. Thanks
    Simply check if the event is scheduled, and if not, schedule it: add_action( 'init', function () { if ( ! wp_next_scheduled( 'my_scheduled_event' ) ) { wp_schedule_event( time(), 'hourly', 'my_scheduled_event' ); } } );
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "plugin development, wp cron" }
    What's the name of the custom post type yearly archive template? I know there's a name for every kind of template. archive-CPT.php, or single-CPT even taxonomies taxonomy-taxonomyname.php but, what's the name I should use for the template that have my yearly archive?
    CPT's don't have date archives, those are a `post` specific feature. Having said that, nothing prevents you building a custom bespoke date archive for a CPT. Just don't expect WordPress core to do it for you, it would be a 100% custom job, you'd have to load your own date templates, modify the query, add the rewrite rules, and construct the URLs yourself. The closest you can get out of the box, is visiting a CPT's archive, and appending query args to the URL, e.g. `example.com/yourcpt?year=2022`, but this will give you the same archive as that URL but with the additional filtering to 2022. Note that this only works with standard archives, it will not work if you replace the main query, rely on page templates to recreate archives, or use a page builder. It also won't be considered a date archive by WordPress functions and APIs
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "custom post types, custom taxonomy, archives, custom post type archives" }
    Add Line Break/Remove Commas for Checkbox options sent via Email from Contact Form 7 Currently when someone submits a contact form that contains multiple checkbox options, when it comes through via email it’s all on the same line split by commas. Is it possible to change the Contact Form 7 email format so it instead adds a line break and removes the commas for checkbox options? We do want it to remain as it is on the actual contact form (where the options are all in one line/a paragraph, not split up by line breaks) – just want the email results to change. **So for example we would like to checkbox results sent via email to showing:** Eggs, Bread, Milk, Water, Oranges **To this (without the bulletpoint):** * Eggs * Bread * Milk * Water * Oranges Is this possible? And if so how would we configure this to work?
    yes, this is possible using the CF7 `'wpcf7_mail_tag_replaced'` filter, add_filter('wpcf7_mail_tag_replaced', 'format_chackbox',10,4); function format_chackbox($replaced, $submitted, $is_html, $mail_tag){ //you can check if this is the right field if need be. if('my-checkbox-field' != $mail_tag->field_name()) return $replaced; //$submitted contains the raw submitted data. //$replaced is the formatted data, you can use either. $a = explode(',', $replaced); //check if you have multiple values and the email accepts html (set with the use html checkbox in the mail notification settings). if(is_array($a) && $is_html){ $replaced = '<ul>'.PHP_EOL; foreach($a as $v) $replaced .= '<li>'.trim($v).'</li>'.PHP_EOL; $replaced .= '</ul>'.PHP_EOL; } return $replaced; } place this in your `functions.php` file
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "plugin contact form 7" }
    How do I modify the custom footer text and get theme version number to show in wordpress admin? I am trying to modify the footer text inside the wordpress admin and also get my custom themes version number to show as well but my function is not working properly, I am still very green at PHP ~ Thank-you in advance! function modify_admin_footer() { echo '<span id="footer-thankyou">Developed by <a href=" target="_blank" rel="noopener noreferrer">Toolcart Theme Version:</a>.</span>'; wp_get_theme()->parent()->Version; } add_filter( 'admin_footer_text', 'modify_admin_footer' );
    Try returning your span instead of echoing it. function modify_admin_footer() { return '<span id="footer-thankyou">Developed by <a href=" target="_blank" rel="noopener noreferrer">Toolcart Theme Version:</a>.</span>' . wp_get_theme()->parent()->Version; } add_filter( 'admin_footer_text', 'modify_admin_footer' );
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "php, functions, wp admin" }
    paypal not showing on woocommerce payments ![enter image description here]( Had install a fresh wordpress installation on localhost, and after install woocommerce plugin, the paypal default - payment isnt there on woocommerce tab "payments". On the live website paypal continues working just fine. Do I need a plugin now, anyone knows something about it
    Paypal standard is now hidden for new installs, possible to read about it in < for those who want to use it copy paste this code on functions.php add_filter( 'woocommerce_should_load_paypal_standard', '__return_true' ); Since july 2021 woocommerce recommends users to use the recommended PayPal extension instead
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 1, "tags": "woocommerce offtopic, paypal" }
    wp-mail attachment is not sent for no reason? I'm using wp-mail to send an image. The problem is that it does not attach the image ! Here is `$attachment_img` string : ` So the path is correct Here is the function : function send_mail_to_admin($orderId , $attachment_img){ $headers = array('Content-Type: text/html; charset=UTF-8','From: انجمن آبزیان <[email protected]>'); $body = "<html><body> <b style='font-size:14px;direction:rtl;text-align:center;'>یک مشتری سفارش با شماره $orderId ثبت کرد</b> </body></html>"; wp_mail( "[email protected]", "دریافت نامه کاربر", $body, $headers , array($attachment_img) ); }
    I changed the code to this and it worked ! Don't know why I should do this and this is very odd but whatever. function send_mail_to_admin($orderId , $attachment_img){ $attachment_img = str_replace(" , "" , $attachment_img); $attachment_img = array( WP_CONTENT_DIR . $attachment_img ); $headers = array('Content-Type: text/html; charset=UTF-8','From: انجمن آبزیان <[email protected]>'); $body = "<html><body> <b style='font-size:14px;direction:rtl;text-align:center;'>یک مشتری سفارش با شماره $orderId ثبت کرد</b> </body></html>"; wp_mail( "[email protected]", "دریافت نامه کاربر", $body, $headers , $attachment_img ); }
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "plugins, php, directory, wp mail" }
    How to send variable to wp meta_query value? I try to to make compare by company title so I need to send this title as variable to meta query value. I use this code and get value = NULL. Please tell me why? $company_name = the_title( ); $params = array( 'meta_query' => array( array( 'key' => 'user_company', 'value' => $company_name ) ) );
    Use `get_the_title` to get the title. `the_title` is for when you want to output directly to the browser.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "meta query" }
    Get term from multiple taxonomy I am trying to show all the terms from these taxonomies. However, I can't get them working. Please help, thanks <?php $terms = get_terms( 'taxonomy' => array( 'category', 'profile_status', 'profile_skill') ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ echo '<ul>'; foreach ( $terms as $term ) { echo '<li>' . $term->name . '</li>'; } echo '</ul>'; } ?>
    Your `get_terms` is causing a parse error, you are missing the array part. Also when using `get_terms` take into account that by default it will not return taxonomies that don't have posts attached to them. The proper code would be like this $terms = get_terms([ 'taxonomy' => [ 'category', 'profile_status', 'profile_skill' ] ]); If you want to include empty taxonomies (taxonomies without posts attached to them), do this $terms = get_terms([ 'taxonomy' => [ 'category', 'profile_status', 'profile_skill' ], 'hide_empty' => false ]);
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "taxonomy, terms" }
    hide elements of admin with css file i use woocommerce and woocommerce Product Vendors (< i want hide elements of admin with css file "my-admin.css" I put css file "my-admin.css" at the root of my child theme wordpress and use this code in functions.php. This does not work?!? function admin_css() { $admin_handle = 'admin_css'; $admin_stylesheet = get_template_directory_uri() . 'my-admin.css'; wp_enqueue_style($admin_handle, $admin_stylesheet); } add_action('admin_print_styles', 'admin_css', 11); is this an obselete method? because: when i use this other method in functions.php, it's ok it works add_action('admin_head', 'my_custom_fonts'); function my_custom_fonts() { echo '<style> body, td, textarea, input, select { font-family: "Lucida Grande"; font-size: 12px; } </style>'; } What do you think ? thanks !!! :)
    It's always better to encapsulate your styles in a separate file, so your first example is closer. That said, the documentation for admin_print_styles says quite clearly: > admin_print_styles should not be used to enqueue styles or scripts on the admin pages. Use admin_enqueue_scripts instead.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "admin, admin css" }
    make admin.css in my child theme i want hide elements of admin with css file "my-admin.css" I put css file "my-admin.css" at the root of my child theme wordpress and use this code in functions.php but does not work? there may be an error? thank you ! : <?php /* activation theme */ function wpm_enqueue_styles(){ wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } add_action( 'wp_enqueue_scripts', 'wpm_enqueue_styles' ); /* admin stylesheet */ function wp245372_admin_enqueue_scripts() { wp_enqueue_style( 'my-admin-css', get_template_directory_uri() . '/my-admin.css' ); } add_action( 'admin_enqueue_scripts', 'wp245372_admin_enqueue_scripts' );
    The `get_template_directory_uri()` function gets the URL to the _parent_ theme. The equivalent function for child themes is `get_stylesheet_directory_uri()`. However these days the proper function to use to get the URL for a file in a child theme is `get_theme_file_uri()`: function wp245372_admin_enqueue_scripts() { wp_enqueue_style( 'my-admin-css', get_theme_file_uri( 'my-admin.css' ) ); } add_action( 'admin_enqueue_scripts', 'wp245372_admin_enqueue_scripts' );
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "wp enqueue style, admin css" }
    Variable global scope I'm trying to create a few custom post types, and instead of hard-coding their names I just want to define them as a globally scoped variable. I thought I understood the scope but apparently not. The code below results in an error of `Undefined variable`: $filmLabel = "Films"; $showLabel = "Shows"; function CreatePostTypes() { register_post_type( $filmLabel, GenerateFilmType($filmLabel)); register_post_type( $showLabel, GenerateFilmType($showLabel)); } add_action( 'init', 'CreatePostTypes' ); I've tried using `$GLOBAL` as well, with the same result. Can anyone spot what's wrong?
    Globals are generally discourgaged. You can use define instead. <?php define("FILM_LABEL", "Films"); define("SHOW_LABEL", "Shows"); function CreatePostTypes() { register_post_type( FILM_LABEL, GenerateFilmType( FILM_LABEL ) ); register_post_type( SHOW_LABEL, GenerateFilmType( SHOW_LABEL ) ); } add_action( 'init', 'CreatePostTypes' );
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 1, "tags": "php, variables" }
    Add $args to wp_list_categories I'm trying to add an argument to wp_list_categories of the Categories Widget: function cat_list_show_all( $list, $args ) { $args['show_option_all'] = __( 'All Cateogries', 'textDomain' ) . '<span>' . wp_count_posts()->publish . '</span>'; return $args; } add_filter( 'wp_list_categories', 'cat_list_show_all', 10, 2 ); But, it return "Array" on front-end. What's the right way to do it?
    The documentation for the `wp_list_categories` filter says that it: > Filters the HTML output of a taxonomy list. So it filters the final HTML, not the args, but you're returning `$args`, which means that the final HTML is replaced with the args array. That's why you're seeing "Array". To filter the args for the categories list in the Categories widget, you need to use the `widget_categories_args` filter. function cat_list_show_all( $args ) { $args['show_option_all'] = __( 'All Cateogries', 'textDomain' ) . '<span>' . wp_count_posts()->publish . '</span>'; return $args; } add_filter( 'widget_categories_args', 'cat_list_show_all' ); However, be aware that this filter only works for the "legacy" Categories widget. Newer sites will only have access to the Categories _block_. The Categories block does not have an equivalent filter, so filtering the args is not possible.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "categories, filters" }
    Multisite login - registration is duplicated I am running a Multisite installation of Wordpress that runs WooCommerce. There six subsites, three of which are a traditional B2C retail and another three that are B2B Wholesale. Anybody can access the B2C (they are territory dependent), create an account and transact. The B2B is different; we manually create the accounts for our Wholesale customers. * **B2C** \- www.domain.com/my-account * **B2B** \- www.domain.com/wholesale/my-account So we have have noticed that if the Wholesale customer goes to the B2C my account page mistakingly and uses their B2B credentials then they are logged in and a new registration is created there. SO they now have access to both the B2B and B2C sites which can lead to confusion. How I can prevent this auto 'dual' login
    By default WordPress Multisite indeed has a shared user base. So, there is no new registration created in de B2B site. It is simply the same registration for all six sites. Of course, this can be modified. You could try programming this yourself, but there are plenty plugins that will do this for you. We don't do software recommendations around here, but you could try googling for "wordpress multisite user management plugin".
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, multisite" }
    Automatic excerpt is not shown with the_excerpt() command I've been looking for an answer to this question for a long time, but haven't found anything: how come when I use the_excerpt() on a given site it doesn't automatically print the first few characters of the content? The excerpt only prints it if something has been added to the WordPress summary field of the post. How can I fix this problem? With other sites this does not happen and if no text is added on the summary the excerpt is generated automatically. What could it be that the excerpt is not automatically generated? My situation is similar to this: Automatic Excerpt Not Working but your response did not provide me with any advice unfortunately.
    By default, `the_excerpt()`, doesn't uses the post/page content wysiwyg, it has its own textarea, that by default is not visible, you need to enable it first via screen options. ![enter image description here]( After you checked this checkbox you can scroll down to the bottom of the post/page and see a new textarea, this is the excerpt. ![enter image description here]( If you want to use the content (wysiwyg, `the_conetnt()` or `get_the_content()`) as excerpt, you will need to use wp_trim_words. Something like this. // the second argument is how many words to trim, default is 55 <?= wp_trim_words(get_the_content(), 30); ?> Anothe option, if you want to keep the html structure would be to do this. <?= force_balance_tags(html_entity_decode(wp_trim_words(htmlentities(wpautop(get_the_content())), 30))); ?>
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "php, excerpt" }
    Conditional Generation of Image Sizes using add_image_size The add_image_size function is used to add image sizes in addition to the default thumbnail, medium, large, & full which are generated in WordPress by default. Is there any way to only add those image sizes for specific uploads? Or are we limited to generating all possible image sizes for every upload?
    Take a look at the intermediate_image_sizes_advanced filter. This filter receives the attachment ID in question, so with that you should be able to work out whether or not you want the intermediate sizes, and return an empty array if not.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "plugin development, theme development, images" }
    Automatically download, install and activate plugins that my plugin depends, how? I'm developing a plugin that requires a couple of plugins from WordPress repository to work correctly. Is it possible to download and install from WordPress repository and activate one or more plugin that my custom plugin requires automatically on plugin activation? There is a safe and correct way to do this via PHP?
    TGMPA is a useful php class to perform the required actions: <
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 1, "tags": "plugins, plugin development" }
    How to change widget title in wordpress version 5.8.1? Maybe this is a novice question but I am stumped. I am trying to change the title of a widget (recent posts) in WordPress 5.8.1 version. I have installed WordPress after a long time again and can not seem to find the option to change a widget title. How to do this? Please remember that I do not want to change the title programmatically as I can do that. Just want an easy point and click option like the old WordPress. I have attached a screenshot of the widget admin screen. ![enter image description here](
    In WordPress 5.8 the ability to add Blocks to widget areas, and several core widgets were replaced with Blocks. Blocks do not have a standardised title field. So to add titles you will need to use a heading bock, and for any blocks that do have a title, whether or how a title can be changed would depend entirely on the block.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "widgets, widget text" }
    Mass SQL Wordpress Meta Key deletion hi i am newbie with SQL data base so forgive my dumbness i have installed KK Star rating plugin on my wp site which noticed its recording lot of entries and my db size is over 280 MB and 188MB is wp_postmeta table. uninstalled the plugin and i want to run sql query to delete all postmeta with kkstar recorcs. the meta key record is: kksr_fingerprint_default so please give me correct command line to run thanks in advance
    DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' {PREFIX} is the string `$table_prefix` defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "plugins, post meta, mysql" }
    Set a specific page as 404 - not found via my own plugin I'm developing a plugin that create some pages and set a specific template for each of these pages. It creates a page in which it sets a template for 404 - not found, how can set this specifc page as WordPress 404 (so it will be displayed when needed)?
    You can filter `404_template` and return the path of your custom file from the plugin directory like this: add_filter( '404_template', fn() => plugin_dir_path( __FILE__ ) . '404.php' ); This hook exists only when a 404 happens, so you don't need any custom detection.
    stackexchange-wordpress
    { "answer_score": 4, "question_score": 2, "tags": "plugin development, pages, 404 error" }
    i need to let a user to add a role from a frontend form i need to let a registered user who already has role or 2 roles the ability to add himself a role via frontend form. i tried to look for it and didn't find anything related that can help me. any ideas? thanks.
    I think each user can only have one role. However this is how its possible to change role, if for some reason that I dont know the user can have more than one role, remove the remove role line. you can check the available roles here. $current_user = wp_get_current_user(); // Remove role $current_user->remove_role( 'subscriber' ); // Add role $current_user->add_role( 'editor' );
    stackexchange-wordpress
    { "answer_score": -2, "question_score": 0, "tags": "users, user roles" }
    Get posts that do not have the same tags as current I'm trying to get all posts in a custom plugin loop that DO NOT share the same tag as the current one. I'm trying: $events = tribe_get_events([ 'start_date' => 'now', 'eventDisplay' => 'list', 'posts_per_page' => 3, 'tag' => $current_tag // <-- Trying to do the exact opposite of this ]); I'm using < 's plugin. But under the hood, that just uses the normal WP args setup. Is there a way to invert the tag selection to get posts that DO NOT have that tag?
    I found an answer to my own question: If I use the `tax_query` arg then I could specify `'operator' => 'NOT IN'` like so: $events = tribe_get_events([ 'tax_query' => array( array( 'taxonomy' => 'post_tag', 'field' => 'name', 'terms' => $current_tag, 'operator' => 'NOT IN' // HERE ) ), 'start_date' => 'now', 'eventDisplay' => 'list', 'posts_per_page' => 3, ]);
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "wp query, loop, tags, query posts" }
    How do I include SVG file used as featured image? I'm new, can I use include() or get_template_part to load an SVG file uploaded as featured image directly in the HTML page? I need to animate the svg images, but i need to easily change the image on each page. I have tried this code but does't work, I can't find the right path, I can load only the svg images in the same folder. $domain = get_site_url(); $svg_url = get_the_post_thumbnail_url(get_the_ID()); $svg = str_replace( $domain, '', $svg_url ); echo $svg; //only for read the url get_template_part($svg); // or inlcude $svg;
    First, you don't need the URL but the server path to the file, you can get it with `get_attached_file` function, passing any WordPress attachment ID as a parameter. Then you need to load the contents of that SVG file directly, via `file_get_contents` function and echo it out to the page. $thumbnail_id = get_post_thumbnail_id( get_the_ID() ); $thumbnail_path = get_attached_file( $thumbnail_id ); echo file_get_contents( $thumbnail_path );
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "php, svg" }
    Will I get an error if I try unscheduling a WP Cron scheduled task that wasn't scheduled? So, I'm developing a plugin, I wanted to know if I call $timestamp = wp_next_scheduled( 'scheduled_hook' ); wp_unschedule_event( $timestamp, 'scheduled_hook' ); Without checking if it's scheduling at all, will it give me an error or will it just go through it and unschedule it in case it is actually scheduled and ignore it otherwise?
    So yeah, it does give errors for trying to unschedule something that isn't scheduled, but the answer is pretty easy and simple: $timestamp = wp_next_scheduled( 'scheduled_hook' ); if ($timestamp) wp_unschedule_event( $timestamp, 'scheduled_hook' ); Since `wp_next_scheduled` will return false for unscheduled hooks, a simple `if` in front of the call to `wp_unschedule_event` will prevent it from being called it there's nothing scheduled
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "plugin development, wp cron" }
    Applying WP-cli Search & Replace to Static SQL Dump File I have a wp db dump file inside my site directory. Can someone show me an example of how to use wp-cli search and replace command on the static sql file, not the active db to change my url from "old-example.com" to "new-example.com" /var/www/html/wp-site.com/dumps/oldexample.com/dumpeddb.sql /var/www/html/wp-site.com/dumps/newexample.com/ready-for-import.sql Not quite sure how to apply this to already exported db dump. `$wp search-replace foo bar --export=database.sql`
    This is not possible, WP CLI uses SQL queries to acquire and update information. You would need to import the SQL file into a database to perform a search replace with WP CLI.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "customization, database, search, mysql" }
    Put featured image under post title in admin area Instead of inserting a new column with a featured image on it, I would like to put the featured image under the post's already existing title. I can't seem to figure out how you insert things on the title property however. Achieving this: ![enter image description here]( I've found this post: How can i place Feature Image under title field in wp-admin? With a snippet that I can't get to work. Otherwise there are lots of solutions for adding new columns with featured images in them. I've arrived at something like this: add_action('admin_head-edit.php', function(){ add_filter('the_title', function( $title, $id ) { return $title . get_the_post_thumbnail_url(); }, 100, 2); }); But if I use `get_the_post_thumbnail_url` the url is embedded as part of the title, and if I use `the_post_thumbnail( 'thumbnail' )` it renders the image twice.
    add_action('admin_head-edit.php', function(){ add_filter('the_title', function( $title, $id ) { return $title . the_post_thumbnail( 'thumbnail' ); }, 100, 2); }); Will produce 2 images because there are two titles on custom posts, apparently. One that is hidden and one that isn't. Adding the image markup to the hidden element will break the CSS that hides it. So the solution is to insert admin-css that hides it. .column-title .hidden ~ img{ display: none; }
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "custom post types, wp admin, post thumbnails" }
    Polylang : Display term archive even if no posts I use ACF to customize **taxonomy term archives pages** which are in fact **Team member pages**. Pages are translated with the help of Polylang. Problem is : If the member has no related posts, I can access directly the member page, but the translated page is not linked to the language switcher menu. Instead it has been replaced with a link to translated homepage. I found that this is common behaviour in Polylang. It is programmed to never show translated pages with no posts. After some research, if found this filter that might be helping. It has been added a while ago but there is no sign of it in the Polylang documentation. Anybody knows how to use is ? Thanks
    Solution given by filter author : add_filter( 'pll_hide_archive_translation_url', '__return_false' );
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "terms, custom post type archives, plugin polylang" }
    Display Current Date using shortcode I am using the below code to display current date in php using shortcodes for Indian time zones: add_shortcode( 'current_date', 'mth_footer_date2' ); function mth_footer_date2() { ob_start(); date_default_timezone_set("Asia/Kolkata"); echo gmdate("jS F Y"); return ob_get_clean(); } We need to add `[current_date]` Shortcode to display current date. This code is displaying date but I think, this is not in Indian Timezone. Please provide me such codes to display time in Indian Timezone. I want Date in following format, **Sunday, 24th October, 2021**. Also provide ways to show tomorrow date in same format.
    You need to use `date()` in place of `gmdate()`, which returns the date/time for GMT. To get the output you want, change the code to: echo date('l, jS F, Y'); For displaying tomorrow's date, use the following code accordingly: $timestamp = strtotime('tomorrow'); echo date('l, jS F, Y', $timestamp);
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "date" }
    How do I add nopin="nopin" to the default avatar? I noticed that if someone clicks on my Pinterest share button on a blog post, several unrelated images show up. I was able to use _nopin= "nopin"_ per Pinterest's documentation on most of these images to clean most of it up. However, I have a custom avatar set in my functions.php... //* Add new default gravatar to Settings » Discussion page */ add_filter( 'avatar_defaults', 'wpb_new_gravatar' ); function wpb_new_gravatar ($avatar_defaults) { $myavatar = ' $avatar_defaults[$myavatar] = "Default Gravatar"; return $avatar_defaults; } If someone gets that avatar in a comment, then the image shows up as a choice on a Pinterest share. How do I add the _nopin= "nopin"_ attribute to this avatar image? I found a similar post discussing this issue, but it's way over my head and seems a little different because he's using an array (lol, also over my head). Any help is greatly appreciated!
    You can try this one: function wp_ste_add_nopin_args( $args ) { $extra_attr = 'nopin="nopin"'; $args['extra_attr'] = $extra_attr; return $args; } add_filter( 'get_avatar_data', 'wp_ste_add_nopin_args', 999, 1 ); For further reading, please visit: <
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "customization, avatar, gravatar" }
    wp-json how to fetch image link? i'm trying to fetch some data and images. everything is working good, but i'm really tired to fetch the post thumbnail image. $data = array( ':attachment' => $record['_links']['wp:attachment'][0]['href'], ); the above code fetching media link such as ` but i want to fetch like that ` how i can do that? please try with a wordpress website with wp-json to see the structure.
    i already fix this by using this $data = array( ':attachment' => $record[_embedded]['wp:featuredmedia']['0'][source_url] ); thanks for no person answered my question.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "json" }
    Add attributes to wrapper html generated by wp_nav_menu I want to add some extra html attributes to the default div html generated by wp_nav_menu. I need to add simple code for example a short style code: `style="top:10px;"` _I can't do what I am doing in a css file_ ; _the html needs to be added in the php_. I have looked at many examples, of walkers, replacement codes like str_replace. I can't find a solution that functions the way I envision it exactly. I prefer to not use a walker code that is ten pages long php code just for doing this simple code addition. If there is not a simple way, the alternative is to wrap the menu in a second div and that is what I will do probably if I can't find another way; but I would prefer to learn a simple way to add the html code to the original div generated by wp_nav_menu.
    Modifying the wrapper for the `wp_nav_menu()` is customizable with the `items_wrap` parameter. < The documentation states that the default wrapper is a `<ul>` element with an ID an CLASS attribute. This can be modified as you wish by modifying the markup passed to the `sprintf()` function used by `wp_nav_menu()`. The value for `items_wrap` is the argument passed for the wrapper. To output a `<div>` element with a style attribute: wp_nav_menu( array( 'items_wrap' => '<div style="css here">%3$s</div>' ) ); The `%3$s` in the example represents the items within the wrapper HTML.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "menus, walker" }
    JSON REST API Wordpress only showing first 10 categories Alphabetically ordered categories are shown first (first 10). If I try to show all categories in JSON / Wordpress, it's not showing it. So, imagine these are the categories: A B C D E F G H I J K (=10) L = not shown anymore How can I make sure I fetch them all? I am trying to fetch them in Dart via JSON, so I can only pass that to Dart. Is there a way I can achieve this?
    This is normal behaviour, you've not accounted for pagination. The REST API returns 10 results per page by default, and can be configured to return up to but no more than 100 per page. You may be tempted to try `-1`, but this will not work, 100 is the maximum results per page that can be requested for performance and scaling reasons. WordPress provides 2 http headers indicating the total number of pages, and the total number of results across all pages so that you know how many requests are needed to fetch all results. I _**strongly**_ recommend reading the REST API handbook in the official documentation. This page covers how to use and control pagination, sorting, etc.
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "php, categories, rest api, json" }
    How to not display tags with less than X posts Is there a way to avoid displaying tags which have less than X Posts? the answer here is close Remove from Google Tags with less than 2 posts however it suggests to send a respose header to google. I would ideally like to NOT have these tags in my sitemap so that google does not index these pages which are basically duplicates of the original post with a different tag, not a good thing for SEO!
    Tags don't create duplicate posts, so the likelihood of them hurting your SEO by appearing in a sitemap are slim. You can add a filter to the return of the taxonomies sitemap to remove tags. This is just a quick attempt I threw together. I haven't tested it but it should provide a basis to work from at the very least. function remove_low_tags($taxonomies) { //create a new array of tags with count above 2 array $allowed_tags; //loop through current array of tags and add them to $allowed_tags if they are > 2 foreach ($taxonomies as $tags) { if (count($tags) > 2) { $allowed_tags[] = $tags; } } return $allowed_tags; } add_filter('wp_sitemaps_taxonomies', 'remove_low_tags');
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "wp query, tags, conditional tags" }
    I'm getting a 401 while calling the wp-json endpoint via ajax **N.B. Resolved - I hadn't noticed it was a POST rather than a GET.** I'm trying to use an AJAX call from a front end page to pull a list "Staff" (custom post type). I can get the data in the browser via wp-json/wp/v2/staff but I get a 401 when I try to pull the data via AJAX. I'm assuming I need to authenticate somehow but can't work out how to to do it. Thanks in advance.
    I had accidentally created a POST rather than a GET. Obviously, you need credentials if you post.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 1, "tags": "ajax" }
    Why would the child theme load in the Customize preview, but not on the site itself? I have my child theme folder, the style.css sheet with the required template comment and some custom css, and I have the functions.php page with the required enqueing code. Everything seems to be in order, except that my custom css is not reflected on my website. However, it _IS_ reflected in the Wordpress Customize screen. Why would this be the case, and how would I get my site to display the custom CSS?
    It appears to work correctly now, I do not know why emptying the cache didn't work before to allow the changes to show but it seems to work correctly now.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "php, css, child theme, theme customizer, wp enqueue style" }
    Using a filter to change a path I know this is probably basic Wordpress coding but how would I achieve this? > Use the filter “wcvendors_pro_table_display_rows_path” — and return a path to the new template file. (/plugins/wc-vendors-pro/public/class-wcvendors-pro-table-helper.php Line #328.) Line #328 of plugins/wc-vendors-pro/public/class-wcvendors-pro-table-helper.php is: public function display_rows() { include apply_filters( 'wcvendors_pro_table_display_rows_path', 'partials/helpers/table/wcvendors-pro-table-data.php' ); } I have created a duplicate of wcvendors-pro-table-data.php in my child theme.
    Create the template you want to use, say `wc-vp-table-rows.php`, put it in your theme, and add the following to your `functions.php`: add_filter( 'wcvendors_pro_table_display_rows_path', fn() => locate_template( 'wc-vp-table-rows.php' ) ); `locate_template()` returns a complete path; it also searches in parent and child themes.
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "woocommerce offtopic, filters" }
    How do I override template-tags.php in 2021 theme I've created a child theme and I want to overwrite functions in inc/template-tags.php file. I thought if I copy this file and recreate folder structure in my child them then it will work but it doesn't? How to do it properly?
    Notice how the parent theme checks if they are already defined e.g. if ( ! function_exists( 'twenty_twenty_one_entry_meta_footer' ) ) { ... } Then just define them in your child theme's `functions.php` file, to override the corresponding template tag. It should work because the child theme's `functions.php` file is loaded before the parent's `functions.php` file that loads: // Custom template tags for the theme. require get_template_directory() . '/inc/template-tags.php';
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "theme twenty twenty one" }
    Product subcat with duplicate name of a subcat of another cat gets the category name in the slug Suppose the following categories tree in Woo: Men (slug men) -- Shoes (slug shoes / was created first) Women -- Shoes (slug shoes-women / was created second) Why is this happening? Both subcats belong to different categories. Why is the category slug appended to the name of the second _duplicate_ subcat? And anyway, for whatever reason Autommatic decided to program it that way, I need to change it, as the nature of the e-shop I'm building is full of such _duplicate_ subcat names, as it will sell clothing, and there will be the same subcat and even subsubcat names for many categories (Men, Women, Kids, etc)... Any insight on this?
    It took me two days to figure this out in the proper way, so I'll add it here for anyone else that may need it in the future. add_filter('wp_unique_term_slug', 'prevent_cat_suffix', 10, 3); function prevent_cat_suffix($slug, $term, $original_slug) { if ($term->post_type == 'product' && $term->parent !== 0) { return $original_slug; } return $slug; } As you can see in the code, I've narrowed it down to products only, but you can make it suitable for any other post type also by removing the `$term->post_type == 'product' &&` in the code above.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 1, "tags": "hierarchical" }
    Get last published post in Wordpress using wp-cli I'm using below `wp-cli` command to get latest post ID: `wp post list --order='DESC' --orderby='ID' --field='ID' | head -1` This, however is inefficient as all posts are retrieved from DB and then `head` limits the number of returned posts. Is there a way to limit the number of returned posts using wp query?
    Simply add: --posts_per_page=1 to limit the queried items to a single item.
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 1, "tags": "wp cli" }
    Block to Popup Page, on demand? I have embedded HTML in a block which renders a Python console. What I want to do is to be able to pop-out the Block in a separate window. If that is not possible then may be a link that when I click on it pops-up a page that contains the console. How do i do that ? * * * I don't want the pop-up to be full-screen. I want to be able to move it around, so the text below can be seen. The HTML can be anything, I just give it as example. Let say : <div id=ABC>12345</div> * * * i know js/html/css but no idea of how wp works... Do i just embed html link with onclick=window.open(...) pointing to a wp-page ? Ooo but i have to somehow make it pure page i.e. no theme !! HOW? And second i have to hide ABC ! * * * Got it : < here is working : < dont look at the site ... it is still under construction ;)
    Solved it : < here is working : < First install the “Blank Slate” plugin. Create New Page Leave the Title empty Set in Page property Template=”Blank Slate” Add whatever content you want Because there is no Title, we need set a Permalink so that is human readable, let say : your-site/blah Publish the page Go to the page you want to have the popup window show up on clicking a link Add the following code : <a href='' onclick='window.open(" target='blank'>Popup window</a>
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "pages" }
    Custom meta_query order for Elementor based on post meta key I'm failing at writing an Elementor `$meta_query` function so posts will be ordered by `meta_value_num` of a given key. Each post has a numeric value for the key `google_unique_page_views` My example is below: // Custom query to order 'recommended reading' posts by populatrity add_action( 'elementor/query/my_custom_filter', function( $query ) { $meta_query = $query->get( 'meta_query' ); if ( ! $meta_query ) { $meta_query = []; } $meta_query[] = [ 'order'=> 'DESC', 'key' => 'google_unique_page_views', 'orderby' => 'meta_value_num', ]; $query->set( 'meta_query', $meta_query ); }); Do I need to include the `value` query?
    Assuming that you want to get posts with that meta key, regardless of content, and order by that meta value, you would need to set two properties. 1. meta_query 2. orderby So the code, based of your question would be like this // Custom query to order 'recommended reading' posts by populatrity add_action('elementor/query/my_custom_filter', function ($query) { if (empty($meta_query = $query->get('meta_query'))) $meta_query = []; // add our condition to the meta_query $meta_query['google_unique_page_views'] = [ 'key' => 'google_unique_page_views', 'compare' => 'EXISTS', ]; // set the new meta_query $query->set('meta_query', $meta_query); // set the new orderby $query->set('orderby', [ 'google_unique_page_views' => 'DESC' // or ASC, based on your needs ]); });
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 1, "tags": "wp query, filters, meta query" }
    How to get current cart values using WC_Shortcodes? I am trying to get current cart items from my own plugin using WC_Shortcodes::cart(); this will return cart details in html format. WC()->cart->get_cart(); code not working. i need only cart data without html format. please advise thank you.
    You can get the value by using the global var global $woocommerce; $cart_value = floatval( preg_replace( '#[^\d.]#', '', $woocommerce->cart->get_cart_total() ) ); Or WC()->cart->total
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "plugins, php, functions, shortcode" }
    How can I add a UTM tag with PHP code to pick up the post slug dynamically in the UTM? The thing I want to do is doable, but I don't know how to do it. Embarrassment moment coming up: I actually did this a few years ago but lost the code and can't find online how it's done. What I want to do is to add a dynamic UTM tag on a link in my header so that the UTM tag picks up the slug of the page the visitor is clicking from. Example: If the visitor is on a post with the slug /something-goes-here/ and clicks on the CTA button, the CTA page that he goes to should have /second-page/?utm_source=something-goes-here Do you guys know how this can be done with a bit of code in PHP?
    What comes to mind is getting the current post by `global $post`, next getting the post slug by `$post->post_name`, next checking the slug if it needs to update a link with a utm query. So something like this. // get the current post global $post; // get the post slug, if not set then set it to empty string $post_slug = $post->post_name ?? ''; // an array of slugs that need to add utm to link $utm_slugs = [ 'slug-1', 'slug-2', 'slug-3' ]; // set default value (empty string), in case no slug was matched $utm_query = ''; // if post slug exists and in the utm slugs array, set a utm query if (!empty($post_slug) && in_array($post_slug, $utm_slugs)) $utm_query = '?utm_source=' . $post_slug; Now that we have the php part taken care of we need to create the link. This is just an example so change it accordingly. <a href=" $utm_query; ?>">Some link</a>
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "php, google analytics" }
    Gutenberg custom block using only register_block_type() and HTML I have the following core block HTML <!-- wp:group --> <div class="wp-block-group"><!-- wp:heading --> <h2 id="hello-world">Hello world</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>Lorem ipsum dolor...</p> <!-- /wp:paragraph --></div> <!-- /wp:group --> Is it possible to create a custom block from PHP using that HTML? Similar to as I would create Patterns? register_block_type() can be used to register blocks from PHP. Is it possible to simply pass the HTML to `register_block_type()` and create the custom block?
    No, blocks are built with more than HTML - they need JS and PHP. However, you could add an HTML block wherever you need it, then click the More Options dots in the block's toolbar, click Add to Reusable Blocks, name your block, and save it. That block will then be available to use wherever you want it, and if you edit it, that will apply the changes everywhere.
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 2, "tags": "php, block editor, json" }
    How to add a CSS class to this php code How can I add a CSS class to "هر متر طول" in this php code: add_filter( 'woocommerce_get_price_html', 'themefars_text_after_price' ); function themefars_text_after_price($price){ global $post; $product_id = $post->ID; $product_array = array( 1204,1202 );//add in the product IDs to add text after price if ( in_array( $product_id, $product_array )) { $text_to_add_after_price = ' هر متر طول '; //change text in bracket to your preferred text return $price . $text_to_add_after_price; }else{ return $price; } }
    I am not sure where this html tags are allowed where this text is going, but maybe something like this: $text_to_add_after_price = '<span class="myclass"> هر متر طول </span>'; Change myclass to the class you want to use.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "php, css" }
    How do I use pre_option_{option_name} correctly? I am using a filter to decrypt an api_key that is stored with encryption. I have registered the following hook: // Decrypt API key after it is retrieved add_filter('pre_option_percify_api_key', array( __CLASS__, 'decrypt_api_key') ); The problem is, I cannot get at the stored value in the callback: public static function decrypt_api_key($encrypted) { // $encrypted is empty: echo($encrypted); // ... Am I calling the function correctly? How do I access the stored value of `percify_api_key` within `decrypt_api_key`?
    The `pre_option_{$option}` hook is used to filter the value of the option **before** it's retrieved. You need to hook after the value is retrieved so you can manipulate it. In this case, you can use the `option_{$option}` hook. So your code will look like this: add_filter('option_percify_api_key', array( __CLASS__, 'decrypt_api_key') ); For more info - take a look at the source of the `get_option` function here. Specifically line #225.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "hooks" }
    Edit the_category (); for a hierarchical display For my wp theme I want to use the categories as tags on my posts. Example: ![enter image description here]( The problem is that the category in red must always be the parent and in gold the child. Except that returns the categories to me in alphabetical order and not in hierarchical order, so sometimes I end up with the child in red and the parent in gold ... Knowing that I would only use 2 categories per posts so 1 = the parent and 2 = the child Do you have a solution?
    You could assign the post only to the child category, and call the function like so: the_category( ' ', 'multiple' ); This will output (notice the whitepsace between the anchor tags): <a href=" <a href=" rel="category tag">child</a>
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "php, functions, categories, tags, hierarchical" }
    last_name + first_name orderby with meta_query [solved] I have small issue with orderby. I´m looking solution to orderby ASC (lastname + firstname) example: 1. Selanne Andy 2. Selanne Beeny 3. Selanne Teemu But now it arrays something like this: 1. Selanne Beeny 2. Selanne Teemu 3. Selanne Andy Here is code: $order_by_1 = array( 'meta_key' => 'last_name', 'meta_query' => array( array( 'key' => 'last_name', 'orderby' => 'meta_value', 'order' => 'ASC' ), array( 'key' => 'first_name', 'orderby' => 'meta_value', 'order' => 'ASC' ), ), 'orderby' => 'meta_value', 'order' => 'ASC' ); $usr_1 = get_users($order_by_1); // Array of stdClass objects. foreach ( $usr_1 as $user ) { .... Thanks for the help.
    To do this you need to use named meta query clauses according to the official developer docs for `WP_Query`: > ## ‘orderby’ with multiple ‘meta_key’s > > If you wish to order by two different pieces of postmeta (for example, City first and State second), you need to combine and link your meta query to your orderby array using ‘named meta queries’. See the example below: > > > 'meta_query' => array( > 'relation' => 'AND', > 'state_clause' => array( > 'key' => 'state', > 'value' => 'Wisconsin', > ), > 'city_clause' => array( > 'key' => 'city', > 'compare' => 'EXISTS', > ), > ), > 'orderby' => array( > 'city_clause' => 'ASC', > 'state_clause' => 'DESC', > ), ) ); ``` > < This question was also asked and answered already here: Order by multiple meta key and meta value
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "meta query, user meta, array, order, wp user query" }
    Can you make a custom gutenberg block that allows the gutenberg editor within it? I'm looking to achieve basically a wrapper for a collection of gutenberg blocks. The idea is that I can apply some ACF fields to the wrapper and then allow gutenberg to do whatever it does for the inner content. However, I can't add "gutenberg" as one of the fields in a custom ACF block. The closest thing I can get is a WYSIWYG editor, so that won't work. Has anyone here managed to get something like this working? Either a wrapper, or allowing the gutenberg editor to be nested within a custom block?
    Shucks, no sooner than the second I desperately resort to asking here, I run into the answer. So for anyone else who just wants a straight answer and not some 45 minute video that never gets to the point... acf_register_block_type( array( 'title' => __( 'Wrapper', 'client_textdomain' ), 'name' => 'wrapper', 'render_template' => 'partials/blocks/wrapper.php', 'mode' => 'preview', 'supports' => [ 'jsx' => true, // this is the line that makes it work ] )); That supports jsx line allows you to assign ACF fields to the wrapper and then the user can gutenberg all they want inside it. Your custom block's html needs this in it as well: <InnerBlocks /> That will enable the gutenberg interface when adding your block in the editor.
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "advanced custom fields, block editor" }
    Shop page custom buttons which is visible to only administrator I created two custom button in woocommerce shop page for every products, and i'm trying to do visible this two buttons only for administrator when he/she login as an administrator. ![enter image description here]( add_action( 'woocommerce_after_shop_loop_item', 'product_visibility_button', 5 ); function product_visibility_button() { echo '<div>'; echo '<a class="button" style="margin:10px">BTN1</a>'; echo '<a class="button" style="margin:10px">BTN1</a>'; echo '</div>'; }
    you can use the following code to check if a user is logged in and has a valid role. add_action( 'woocommerce_after_shop_loop_item', 'product_visibility_button', 5 ); function product_visibility_button() { if ( is_user_logged_in() ) { $user = wp_get_current_user(); if ( in_array( 'administrator', (array) $user->roles ) ) { echo '<div>'; echo '<a class="button" style="margin:10px">BTN1</a>'; echo '<a class="button" style="margin:10px">BTN1</a>'; echo '</div>'; } } }
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "customization" }
    WordPress Gutenberg react make import of __experimentalUseInnerBlocksProps which is no more experimetal I have a plugin with import import { __experimentalUseInnerBlocksProps as useInnerBlocksProps } from '@wordpress/block-editor'; but it's not working with newest Gutenberg plugin 11.9, because this `useInnerBlocksProps` is no longer _experimental_ so I can use import { useInnerBlocksProps } from '@wordpress/block-editor'; but then it will not work for older versions, or WordPress installation without Gutenberg plugin. What's the correct way to make it compatible with both scenarios? How to import __experimentalUseInnerBlocksProps if exists and directly useInnerBlocksProps if not?
    Ok, this is probably the easiest workaround I was able to find, but if someone has better idea, then feel free to post it here ;) import { __experimentalUseInnerBlocksProps, useInnerBlocksProps, } from '@wordpress/block-editor'; if( typeof useInnerBlocksProps == 'undefined' ){ var compatibleUseInnerBlocksProps = __experimentalUseInnerBlocksProps; }else{ var compatibleUseInnerBlocksProps = useInnerBlocksProps; } * so basically I can import both (experimental and no-experimental) without any error * then I can just do simple type test if the new one is already supported * if it's supported I will remember it in `compatibleUseInnerBlocksProps` variable * otherwise I will remember old _experimental_ * then I need to replace all other occurrences of `useInnerBlocksProps` with `compatibleUseInnerBlocksProps` in my code
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 2, "tags": "plugins, plugin development, block editor, import" }
    How can I get wordpress slug without certain phrase? I got this code: `<?php echo basename(get_permalink()); ?>` and I get slug of current post page example: "dog-training" And my wordpress posts are like this: domain.com/dog-training/ domain.com/dog-toys/ domain.com/dog-food/ etc. And I need to get the slug but only the part "toys", "food" and "training" so I need to get rid of the "dog-" part. Will You help me with this. I`m not a programmer ? Thanks
    Previous answer here. You'll want to use `str_replace` $permalink = get_the_permalink(); $permalink = str_replace("dog-", "", $permalink);
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "slug" }
    How can I prevent wordpress from creating tag pages? I use the built in wp tag functionality to group my posts thematically and then I use the WP_query to have the posts displayed according to custom design. I do not need the tag pages created by default in wordpress and I would either like to have them NOT created at all (ideally) or be able to add a noindex meta to the post, as these should not be indexed separately. Is there some way to accomplish this? EDIT: one additional possibility I have looked at is to exclude all matching urls from the sitemap eg exclude all urls matchine /tag/* . I use the Yoast plugin, but I don't see any filter which would allow me to do this type of exclusion.
    To redirect from the automatically-generated tag archive pages, you can check to see if `is_tag()` is true in the `template_redirect` action hook, and redirect with `wp_redirect()` if it is: add_action( 'template_redirect', function() { if ( is_tag() ) { // Currently redirects to the site's home page. wp_redirect( '/' ); // Use the 301 Permanent redirect if desired. // wp_redirect( '/', 301 ); exit; } } ); To exclude the tags from the sitemap generated by WordPress (Plan B in your question), you can use the `wp_sitemaps_taxonomies` filter. add_filter( 'wp_sitemaps_taxonomies', function( $taxonomies ) { if ( ! empty( $taxonomies['post_tag'] ) ) { unset( $taxonomies['post_tag'] ); } return $taxonomies; } );
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 1, "tags": "tags" }
    Show popover with url and option to open in new window I am creating a custom block and I want to show a button which the user can edit the text of and I want them to be able to select a page/enter a link. I have this working but using `URLInputButton` does not give the option to open in a new tab like the default wordpress popover when you highlight some text and then choose to add a hyperlink. This is what I currently have: <URLInputButton url={url} onChange={onURLChange} /> I have also played around with a popover but not sure how to put what I want in there. This just does what it says and shows text that says 'Popover is toggled!" <Button variant="secondary" onClick={toggleVisible}> Toggle Popover! {isVisible && <Popover>Popover is toggled!</Popover>} </Button>
    There's no support for such a setting in `URLInputButton`/`URLInput` and those components are deprecated. Try `LinkControl`. It may be helpful to study its use in the core Button block. That seems similar to what you are building.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "theme development, block editor" }
    How to change the date and time in REST API for comments? /** * Add a Formatted Date to the WordPress REST API JSON Post Object * */ add_action('rest_api_init', function() { register_rest_field( array('comment'), 'formatted_date', array( 'get_callback' => function() { return get_the_date(); }, 'update_callback' => null, 'schema' => null, ) ); }); This is not working for me. I am constantly getting the following in my JSON: "formatted_date":false," How can I show it in a format like: `"28 November 2021, 15:00"`?
    In general I would be careful modifying existing endpoints, but you could try using the object passed into the callback, e.g.: 'get_callback' => function( $object ) { return date_i18n( __( 'j. F Y, H:i', 'wpse' ), strtotime( $object['date'] ) ); },
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "rest api, api, date, date time, wp api" }
    How to get tags outside of loop for specific page I'm on? Outside the loop, if I use the following code in my child theme... $mtags = get_tags(array( 'taxonomy' => 'custom_tag', 'orderby' => 'name' )); It prints out all my tags. But how can I only get tags relating to the page I am viewing?
    First you need to get the ID of the page/post/content you're viewing. Then, you can call `get_the_terms()` and pass it that ID so it knows you want the tags for that specific piece of content. <?php $mtags = get_the_terms( get_queried_object_id(), 'custom_tag' ); ?> There isn't an `orderby` parameter, so you may need to sort the array afterward if you want them in a specific order.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "tags" }
    GitHub plugins safe to use in my website? I have some question about GitHub files, I hope it is a proper place to ask. I downloaded the gravity forms from < You may know that the plugin itself is sold by min price 59$/year in its website < I am surprised if it is not free in the original website, how it can be downloaded for free at GitHub? Do you think I can use the version from GitHub without any stability and safety issues? Thanks
    The GitHub repository changelog is updated until version 2.4.20. The official Wordpress is currently updated to version 3.1.25. So in answer to your question, you can see that the GitHub repository appears to be abandoned, and therefore it does pose security flaws and you won’t get updates.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, plugin gravity forms, github" }
    Gutenberg: how to hide server side render output in the editor but keep it in frontend? My goal is to use the Gutenberg Block for the backend editor to collect the data but output it only with php. I added a server-side-render component to my block. Now I can edit attributes in the Gutenberg Editor and output them on the server side with php. But the output is renderer in the editor as well. I don't need that because it displays everything twice. How do I hide the server side render output in editor? Do I prevent the output in php with something like "if is_frontend() {return $output}" or is there an attribute for server side render to keep it off Gutenberg?
    This can be down in the php render_function. Check if it is an API REST request: function create_block() { register_block_type( __DIR__ ,[ 'render_callback' => 'render_php' ] ); } function render_php(){ if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) { return "<p>Backend says hello from php</p>"; } else { return "<p>Frontend says hello from php</p>"; }; }
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 1, "tags": "block editor" }
    Storefront theme : Add Categoy to recent products section I want to modify the Recent Products section Storefront theme to be able to include juste a specific category. i tried that : add_filter( 'storefront_recent_products_args', 'my_custom_storefront_category_args' ); function my_custom_storefront_category_args( $args ){ $args = array( 'limit' => 8, 'columns' => 4, 'category__in' => array ('35') ); return $args; } but no success
    I found it , the question is resolved : Solution : add_filter( 'storefront_recent_products_args','my_custom_storefront_category_args' ); function my_custom_storefront_category_args( $args ){ $args = array( 'limit' => 6, 'columns' => 3, 'orderby' => 'date', 'order' => 'desc', 'category' => 'your-cat-slug', 'cat_operator' => 'AND' ); return $args; }
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "child theme" }
    Get the URL of the page from which an ajax request has been launched within ajax callback I'm calling a server-side function written in PHP via `wp-ajax`. The server-side function eventually redirects to another page for an authentication step, and then redirects back to the initially shown page. For this to work in a generic way, I need to pass the URL from which the AJAX request was fired onto the server-side function. How can I actually do this? When I try for example this, I get the link to `wp-admin/admin-ajax.php`... I know that I could in theory use `window.href`or whatever in js and send that to the server, but I want to avoid this extra-piece of data sent, as I'm thinking that there must be some built-in wp feature for this...?
    Ok got it, knew there must be some built-in WP solution to this. Simply call `wp_get_referer()` in your callback (for details, see this). At least it's working as I need it, let me know if there's any better solution. _**UPDATE**_ Thanks to @Tom J Nowell, we should also mention that referrers could get stripped for privacy reasons or similar. To thus be on the safe side, there's no way around passing the referrer's URL explicitely to the data sent across AJAX, like using `document.location.href`.
    stackexchange-wordpress
    { "answer_score": 3, "question_score": 0, "tags": "php, ajax, urls, site url" }
    Display Ad on Specific Categories I want to display the ad only in specific categories. Can anyone help me here's the code to display the ad on all single posts/ <?php get_template_part( 'template-parts/ads/below-head' ); ?>
    This will display the ad on all posts belonging to the categories listed in the array: <?php global $post; if ( in_category( array('news', 'cats', 'dogs'), $post->ID ) ) { get_template_part( 'template-parts/ads/below-head' ); } ?>
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 1, "tags": "custom post types, posts" }
    how to create a custom page in child theme or plugin? i'm kind of new to plugins . for a project we need to create a special form which normal plugin won't help us . we should create a special form page which insert data to db . the main problem is because of limit of modification of main theme i can not directly do changes i want. my question was is there any way to create that custom page template using plugin or child theme ? every answers will be welcomed :)
    you just need to copy a Page Template from the Parent Theme into your Child Theme and rename that template with the new which you want to set into the site or create a new template PHP file add below code: <?php /* Template Name: -- Template Name -- */​ get_header(); get_footer(); ?>
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "plugins, child theme" }
    Redirect when not logged and parametr in link how do I redirect to 'domain.com/sub' for unlogged users, when the url is without the "one_time_login" parameter? This should not work when a user is trying to login via sub.domain.com/wp-admin. Have no idea. I understand that htaccess cant make this? Thanks for your help!
    This should work for what you're looking to achieve; add_action( 'template_redirect', 'redirect_to_specific_page' ); function redirect_to_specific_page() { if ( ! is_user_logged_in() && ! is_page('one_time_login') ) { wp_redirect( 'domain.com/sub', 301 ); exit; } } This should be added to your theme (or child theme) functions.php file
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "redirect" }
    WooCommerce get_price returning wrong price when used via ajax I'm working on a site that uses the Events Tickets plugin, and I need to get the price of a ticket (Woo product) by ID. I'm using `wc_get_product( $ticketID )->get_price();` to to do this. Adding the price to the page using the code below gives the correct price (e.g. 30): echo '<input type="hidden" id="ticketpricetest" value="' . wc_get_product( 28612 )->get_price() . '">'; However, when I try and get the price using the same method within an Ajax call it returns 300: function get_ticket_price() { $ticketID = $_REQUEST['ticketID']; echo wc_get_product( $ticketID )->get_price(); } add_action( 'wp_ajax_get_ticket_price', 'get_ticket_price' ); add_action( 'wp_ajax_nopriv_get_ticket_price', 'get_ticket_price' ); I've also tried using `get_regular_price` but that also returns 300. Any ideas what's going on here?
    It's important to exit the function when using the wp_ajax hooks. Hopefully this fixes it. function get_ticket_price() { $ticketID = $_REQUEST['ticketID']; echo wc_get_product( $ticketID )->get_price(); // Don't forget to stop execution afterward. wp_die(); } add_action( 'wp_ajax_get_ticket_price', 'get_ticket_price' ); add_action( 'wp_ajax_nopriv_get_ticket_price', 'get_ticket_price' );
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 1, "tags": "plugins, php, plugin development, theme development, ajax" }
    Override a function defined in wp-includes/comment-template.php I need to override the function `get_cancel_comment_reply_link` or `cancel_comment_reply_link` that are defined in wp-includes/comment-template.php These functions are not listed in `pluggable.php`. **How can I override them from my theme's`functions.php`?** I tried remove_filter('get_cancel_comment_reply_link', 'cancel_comment_reply_link'); add_filter('get_cancel_comment_reply_link', function($text='') { return ''; }, 1, 1); without success.
    If you look at the end of the function `get_cancel_comment_reply_link( $text = '' )` in the file `wp-includes/comment-template.php`, you see the filter `cancel_comment_reply_link`. return apply_filters( 'cancel_comment_reply_link', $formatted_link, $link, $text ); It may work.
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "php, functions, filters, actions, pluggable" }
    get_the_ID() in the footer returns wrong value I'm using `get_the_ID()` in `footer.php` but it returns a wrong value. It might come from any of the plugin which is altering The Loop without resetting it after with `wp_reset_postdata()` as mentioned in $post->ID and the_id() always return the wrong value. Indeed the page shows a list of recent posts, etc. so this might modify the current Loop. If I can't modify this (because of third party code), how to **get the ID of the current post** in the footer anyway, with PHP?
    In an environment without third party code, `get_the_ID()` should give you the correct value. It sounds like some plugin is interfering with this. So you can do what they forgot and simply call wp_reset_postdata() in your footer before you need the values.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "php, wp query, loop, id, get the id" }
    How to make content area in full width in Twenty Twenty-One theme? I've a child Twenty Twenty-One theme and I want to make the content area in full with. I don't want to use any plugin. I've searched and found that adding following code in CSS may work but for me it's not working. How to do it with css if it is possible? .entry-content > *:not(.alignwide):not(.alignfull):not(.alignleft):not(.alignright):not(.is-style-wide) { max-width: 87rem; width: calc(100% - 8rem); }
    I figured it out. It is the inherit default layout settings. First turn that off and then enter the desired width.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "themes, theme twenty twelve" }
    How to prevent sending auto emails for specific actions in wordpress How to prevent sending auto emails for specific actions in wordpress, i have a function that generate password for users, only after the admin accept the user application create_user_password($subscription->ID), //this function calls wp_update_user Wordpress sends a message about a (password change action), how to prevent this ONLY if this method was triggered by an admin
    If you look in the documentation of `wp_update_user()` you will see that it uses two filters: * `send_password_change_email` * `send_email_change_email` Simply from the names I would guess if you return `false` in `send_password_change_email` it should work. So something along the lines of: function create_user_password($id) { // other code add_filter('send_password_change_email', '__return_false'); wp_update_user(...); remove_filter('send_password_change_email', '__return_false'); }
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "email" }
    Get posts for which a custom field is not present, with get_posts I'd like to get all posts for which the custom field `hidden` is NOT present. This does not work: $postsForSitemap = get_posts(array( 'numberposts' => -1, 'orderby' => 'modified', 'post_type' => array('post', 'page'), 'order' => 'DESC', 'meta_key' => 'hidden', 'meta_compare' => '!=') ); because `meta_compare` is about the `meta_value`, not the key. I haven't found in the documentation < how to get all posts that _don't have_ a specific custom field. How to do this?
    You could use `NOT EXISTS` as the value for comparem, you could also check for empty value if thats relevant This code only checks if `hidden` meta does not exists $postsForSitemap = get_posts([ 'numberposts' => -1, 'orderby' => 'modified', 'post_type' => ['post', 'page'], 'order' => 'DESC', 'meta_key' => 'hidden', 'meta_compare' => 'NOT EXISTS' ]; This checks is `hidden` meta does not exists OR has no value $postsForSitemap = get_posts([ 'numberposts' => -1, 'orderby' => 'modified', 'post_type' => ['post', 'page'], 'order' => 'DESC', 'meta_query' => [ 'relation' => 'OR', [ 'key' => 'hidden', 'compare' => 'NOT EXISTS', ], [ 'key' => 'hidden', 'value' => '' ] ] ];
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 1, "tags": "wp query, custom field, get posts" }
    Converting Y-m-d to a date with a Month name? So I can easily get today's date with: echo (date("Y-m-d")); The above outputs: 2021-12-06 How do I get 2021 December 06 from the above format? P.S. I will be storing 2021-12-06 into my database. Later I will want to convert this format into the example I gave above. Thanks for your help.
    You can use createFromFormat to re-format your date. Like so: $date = DateTime::createFromFormat('Y-m-d', '2021-12-06'); echo $date->format('Y F d'); If you want your output to be anything other than "2021 December 06", please check PHP datetime formats for all available formatting options.
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "php, date" }
    How do I attach a page to a category similar to how we attach media to a post? Is it possible/how do I to attach a page to a category similar to how we attach media to a post? ps. I'm not asking how to assign a category to a page. update: I need to attach a specific page contents on top of the archive of a specific category archive.
    No, media is attached to posts/pages using the `post_parent` column. This works because media is actually a post of type `attachment` in the database. Categories however are not posts, and the way you would attach them is by assigning the page to that category. This leads us to a contradiction, how do you attach a page to a category without attaching it to a category? I'm sure that your original problem is solvable but this is not the solution.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "categories, pages" }
    how to add display_name from the users table to this query how to add display_name from wordpress users table to this query thanks for the help SELECT a.post_title, b.meta_key, b.meta_value as level, c.meta_value as intro FROM wp_posts a LEFT JOIN wp_postmeta b ON a.ID = b.post_id LEFT JOIN wp_postmeta c ON a.ID = c.post_id WHERE b.meta_key = 'level' AND c.meta_key = '_post_main_intro'
    You should be able to do something like this, by adding in another join, and selecting the `display_name` column from that joined table: SELECT a.post_title, b.meta_key, b.meta_value as level, c.meta_value as intro, u.display_name FROM wp_posts a LEFT JOIN wp_postmeta b ON a.ID = b.post_id LEFT JOIN wp_postmeta c ON a.ID = c.post_id LEFT JOIN wp_users u ON a.post_author = u.ID WHERE b.meta_key = 'level' AND c.meta_key = '_post_main_intro' Hopefully this works for you!
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "php" }
    How to display tags with post_content I have this code to display the content of a specific post outside the loop (actually in the archive.php template file). How do I include the tags? <?php $my_id = 1576; $post_id_1576= get_post($my_id); $content = $post_id_1576->post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo $content; ?>
    Simply use `get_the_tags($my_id)`, example : $posttags = get_the_tags($my_id); if ($posttags) { foreach($posttags as $tag) { echo $tag->name . ' '; } } Refering to WordPress codex
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "tags, post content" }
    Use PHP code to create custom user roles. Call it once? I have the following PHP code in my wordpress site. I have noticed that when I disable the following code, those two user roles still exists both for current and new users. /* ------------------------------ ADD NEW CUSTOM ROLES ------------------------------ */ add_role('barber',_('Barber'),array('read' => true, 'edit_posts' => true)); add_role('barber_shop',_('Barber Shop'),array('read' => true, 'edit_posts' => true)); /* ---------------------------------------------------------------------------------- */ My question is, do I need to call this code once, or should I always keep it running? Will it cause any issue in the future?
    Generally, you would call this code in a plugin activation hook or at the very least, `init`. The issue you _may_ run into is calling this code too early if it's outside any specific WordPress hooks which would cause issues. That being said, `add_role()` calls `WP_Roles::add_role()` and one of the first things it does is check if it's already defined via: if( empty( $role ) || isset( $this->roles[ $role ] ) ) { return; } WordPress saves roles in the options table and grabs those roles on instantiation. If the role is already set, it's just going to return early no harm, no foul.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "user roles" }
    How to use category slug to echo a page's content with the same slug How can I fit this category slug `<?php $term = get_queried_object(); echo $term->slug; ?>` into this page content `<?php $page = get_posts([ 'name' => 'slug-goes-here', 'post_type' => 'page' ]); if ( $page ){ echo $page[0]->post_content;} ?>`
    Worked it out... <?php $term = get_queried_object(); ?> <?php $page = get_posts([ 'name' => $term->slug, 'post_type' => 'page' ]); if ( $page ){ echo $page[0]->post_content; } ?>
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "terms" }
    Display logged in user name and lastname on page I want to display the first an lastname of my users on a welcome site. I have some code in my functions.php that let me show the first name. How can I change the code to show both first and last? This is my code for the shortcode: function custom_shortcode_func() { ob_start(); $current_user = wp_get_current_user(); echo 'Willkommen ' . $current_user->user_firstname . '<br />'; $output = ob_get_clean(); return $output; } add_shortcode('current_user', 'custom_shortcode_func');
    You can always do a `var_dump()` of `$current_user` to see what it contains. You'll see there is a similar property to `user_firstname`: `user_lastname`. You'll probably want a space between the first and last name, so a small edit should add the last name: function custom_shortcode_func() { ob_start(); $current_user = wp_get_current_user(); echo 'Willkommen ' . $current_user->user_firstname . ' ' . $current_user->user_lastname . '<br />'; $output = ob_get_clean(); return $output; } add_shortcode('current_user', 'custom_shortcode_func'); As you can see you're already getting the last name and other data, so the tweak just adds a space character and the last name.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "php, functions, shortcode" }
    Live Streaming with Wordpress? Does anyone know a working set up for a live streaming event delivered by a wordpress page? There should be 500 participants. I have no idea, what I need to consider and which technological set up neccessary to do this. YouTube / Zoom is not an option, because the event should be delivered on an excklusive page with restricted accesss … Best and thank you.
    You can use Jitsi, it’s open source and can be embedded/integrated as you require for member areas etc. Here’s an example plugin that uses it. I have no affiliation with Jitsi or the plugin.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "plugins" }
    Add wordpress to only one domain in shared hosting with multiple domains I got a shared hosting plan with namecheap in which I'm hosting multiple domains. I want to use only one of this domains with wordpress. Can I just install Softaculous Wordpress on my cPanel with any worries. If yes, how can link the domain I want to wordpress? Will the other domains be affected by wordpress installation?
    so from my experience as a WordPress developer, the only downside of the shared hosting is that that's all you got ( in terms of memory ). so if you install Wordpress from the official site and then upload it to the correct path ( let's say you have bought 3 domains: marinario.ko, marinario.com, marinario.it and the primary domain is marinario.com then inside public_html you can upload the zip of WordPress, if you want to create with WordPress one of the other domain then you have to upload it to public_html/marinario.ko lets say. then you can unzip it and move all the files directly to the folder. then you have to create a DB with a user. you can go then to marinario.com ( if you have uploaded it to public_html ) and enter all the data it wants. if you have any problem with hhtps you can add a redirect rule inside cPanel. I hope I have helped you :)
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "hosting, shared hosting" }
    Does the WordPress core software handle bounces on system email? The WordPress core sends a number of system emails, such as for password changes and for form plugins that use the WordPress core. If any of those emails bounce, does the WordPress core receive and handle them?
    The quick answer: no. At least not out of the box. The bouncing email goes to the mail server and if there is no mailbox, catch-all or redirect address set, it will just bounce. You would need to connect WordPress to via pop3 or IMAP to receive emails. There is at least one plugin for using WordPress as a mail client. I am not sure how it works, so I don't know secure it is and how it (potentially) impacts WordPress performance.
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "email" }
    is $wpdb->get_results() safe enough #### original question if I use the get_results() functions is this safe enough from mysql injection attacks? global $wpdb; $wpdb->get_results("select * from tableA where B = C"); Or should this have some kind of prepare first? What's the best practice? How should we do it in our present time December 2021 ? #### update so I should use this instead? global $wpdb; $my_variable = "sometext"; $prep = $wpdb->prepare("select * from tableA where B = %s", $my_variable); $wpdb->query($prep);
    You have to always use $wpdb->prepare() before $wpdb->query() or $wpdb->get_results() if your queries depend on dynamic variables
    stackexchange-wordpress
    { "answer_score": 4, "question_score": 0, "tags": "database" }
    How to limit the number of images displayed in the media window? I have a lot of images in my website, so when I open `wp-admin/upload.php` the server slow down. Would be possible to display only 50 images per time? I saw there is this similar question, but it works only for the "set featured image" popup. I would like to apply the limit also to the `upload.php` window. How can I achieve that? Kind regards
    maybe this other similar question (with a good answer) can help you. Change default screen option value for media items per page (in media library) And the filter to use is : function my_edit_media_per_page(){ $media_per_page = 200; //or whatever you want return $media_per_page; } add_filter( 'upload_per_page', 'my_edit_media_per_page', 10, 3 );
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "images, uploads, media library" }
    Using WP_Mail on MacOS 12 (Monterey - M1) On a brand new Macbook running Monterey (M1), as PHP was removed by Apple on OS 12, I have removed all "AMP" preinstalled by Apple and installed HomeBrew "AMP" (with PHP 7.4), which is running perfectly. Now, as I have setup Wordpress for testing purposes, I am attempting to use Wordpress WP_Mail function, which relies on PHPMailer, which in turn uses PHP Mail command. The latter relies on system specific libraries, and I am bit confused about configuring the correct facility, Mail, SendMail, Mailsend.... Digging the Internet, once upon a time you would achieve this through Postfix or eventually setting up an email account in the System settings for Mail.app , which I would like to avoid, as I only use web mail on browser and hate to have an email client accessing my account......... In conclusion, on a Monterey M1 machine, Homebrew "AMP" scenario, is there a way to allow PHPMailer to work, avoiding using Mail.app account?
    Hi I put this function on the functions.php or in a plugin and works for me everywhere, on localhost or in any server. just need to change the strings to your email smtp settings. Only with gmail I could not make it work so far, all the other ones I try it works perfectly. // Overriding wp smtp email to send smtp emails (no spam emails) if (! function_exists('email_sender')){ add_action('phpmailer_init','email_sender'); function email_sender($mail){ $mail->SetFrom('[email protected]', 'thenameIwant to appear on the emails sended'); $mail->Host = 'smtp-mail.outlook.com'; $mail->Port = 587; $mail->SMTPAuth = true; $mail->SMTPSecure = 'STARTTLS'; $mail->Username = '[email protected]'; $mail->Password = 'mypassword'; $mail->IsSMTP(); } } then email should work like a charm! I normally use `wp_mail()` to do it.
    stackexchange-wordpress
    { "answer_score": 3, "question_score": 0, "tags": "wp mail, smtp" }
    Automatic translation with different domains per languages? I would like to know if there is a plugin to make automatic translations with one different domain by language for the same project. For example : car.co.uk for the English voiture.fr for the French coche.es for the Spanish etc. And still have an automatic translation : If I create a new article in French on voiture.fr, there also an automatic creation and translation on the English version (car.co.uk) and on the Spanish version (coche.es) without any human actions? I know I can’t do this with Weglot (only one domain) so I’m searching an alternative… Thanks a lot for your answers!
    I believe you can do this with WPML. Keep in mind that it's a paid add-on and I have not tested it myself. Check out their page here: <
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "translation" }
    How do I activate my child theme, as I do not see it in developer tools I uploaded a child theme from Astra, but the css or javascript does not display, but I was told to look if it is activated. I have looked in developer tools, and I do not see anything about a child theme there. Would anybody know, how I could activate it, if that is the problem. Thanks
    You can generate your Astra child theme from here. <
    stackexchange-wordpress
    { "answer_score": 0, "question_score": -1, "tags": "plugins, child theme" }
    If you have multiple dynamic blocks with a post loop on a page, how do you avoid duplicates from inside the render_callback function? I'm building dynamic blocks to customize the blog index into more of a magazine style layout, featured posts, categories, other content, all mixed together. My dynamic blocks are able to render a loop and post content just fine, but I cannot pass a list of IDs from the render_callback block function to itself when it displays multiple times on the same page, leading to duplicate posts in this block when used in various places on a page. If you have multiple dynamic blocks rendering a get_posts loop, how do you pass a list of IDs to the next instance to avoid duplicates?
    In PHP I recall these ways 1. Static variables 2. Class properties 3. Databases, Files, Memory (might be flushed though) to preserve a state, in a hook's callback, that is called multiple times in WordPress and in the order I would consider using myself but it depends on the context (eg WP transients, that store data that expires, can use memory for speedy recalling and database as a fallback). Global variables might also be listed at the bottom (usually not recommended) and closure tricks closer to the top.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "block editor" }
    Disable lazy loading on specific images Wordpress adds lazy loading on all images. Lighthouse recommends disabling lazy loading on images in above the folder. I would like to figure out how to disable it only on images that I call with wp_get_attachment_image_src in my templates, so that I can control exactly which LCP images to remove lazy load. Lighthouse documentation:
    You can manage WordPress lazy loading with the `loading` parameter. Below code echo's your image without using the lazy load function. echo wp_get_attachment_image( $image, $size, false, [ 'class' => 'your-class-here', 'loading' => 'eager' ] );
    stackexchange-wordpress
    { "answer_score": 6, "question_score": 0, "tags": "images, performance" }
    splitting the URL using jQuery **Can i get the help of you guys as i want i can do it with url** I need to split the URL. and use last element as job_id, And then pass "jkdbsbd45JubJKAAASSYT" as job_Id. URL: Need to create this URL as below. Need: **Thanx in advance**
    Not really a WordPress related question but you could do this // creates a object from the array, one of the properies (search) contains the query let url = new URL(' // will create a object of all availalble query properites const urlSearchParams = new URLSearchParams(url.search); const params = Object.fromEntries(urlSearchParams.entries()); // remove ? and everything after from url url = url.href.substring(0, url.href.indexOf('?')); // url + params.job_id is the final url, did a console.log so you could see it in the devtools console console.log(url + params.job_id);
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 1, "tags": "ajax, javascript, jquery, jquery ui" }
    Trying to run Javascript on AJAX call I am trying to change the classes for the "View cart" button after adding an item to the cart. What I tried to do is to hook into the "woocommerce_ajax_added_to_cart" action and insert my Javascript as below but this Breaks the AJAX call. I honestly don't know if I am using the correct hook: function set_button_classes() { echo "<script>document.getElementByClassName('added_to_cart wc-forward').classList.add('ct-cart-item', 'ct-offcanvas-trigger');</script>"; } add_action( 'woocommerce_ajax_added_to_cart', 'set_button_classes', 10, 1 ); Any pointers would be really appreciated.
    Found an answer on here. It does work but I am having timing issues I think. They are unrelated to the question though so I will mark the below as the answer. Thanks all. add_action( 'wp_footer', 'trigger_for_ajax_add_to_cart' ); function trigger_for_ajax_add_to_cart() { ?> <script type="text/javascript"> (function($){ $('body').on( 'added_to_cart', function(){ // Testing output on browser JS console console.log('added_to_cart'); // Your code goes here }); })(jQuery); </script> <?php }
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, ajax, javascript" }
    Detect if a block has been deleted I’m currently working on a slider block for the block editor. While I use custom buttons to add a slide (which is a block), I can detect when a new block has been added to tell the slider script to refresh in order to take note of the newly created block (which acts as slide). However, if I want to use the regular "delete block" action from the block's toolbar menu, I cannot find out how to detect that. I was already digging into the code and came to the conclusion that I had to detect when the action gets dispatched. However, I'm quite new to React and thus don't know how to detect the `removeBlock` dispatch action. I thought about subscribing to the store's change but I cannot figure out which store to subscribe on: const unsubscribe = subscribe( () => { console.log( store.getState().lastAction ); // which store? } ); Is this the correct way or is there something easier?
    Maybe you will find this snippet helpful. I'm still searching for a better way to do this but as far as I can tell blocks are not aware of their own deletion. Instead we have to monitor the blocks from above. If you have a parent block type that has children, you can subscribe to core/block-editor and use getBlocks() to check the length of children and if the new length is lower than the old length then you have caught a deletion. const getBlockList = () => wp.data.select( 'core/block-editor' ).getBlocks(); let blockList = getBlockList(); wp.data.subscribe( () => { const newBlockList = getBlockList(); if ( newBlockList.length < blockList.length ) { console.log( 'A block was removed!!' ); } blockList = newBlockList; } );
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "block editor" }
    How to change the link address from internal to external Look at the line below It now reads the file (script.js) from the same folder I want to replace the link to another site for example: ` wp_register_script( 'post_publisher_js', plugins_url('script.js', __FILE__), array( 'jquery' ), "1.0.2" );
    Just replace `plugins_url('script.js', __FILE__)` with `'
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "javascript" }
    I have a snippet to redirect all users to a maintenance page. How do I exclude users with admin role? I have a snippet that redirects all users to a maintenance page. How can I tweak it to All users except admin users? <?php add_action( 'template_redirect', function() { if ( is_page( 4848 ) ) { return; } wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) ); //wp_redirect( esc_url_raw( home_url( 'index.php?page_id=4848' ) ) ); exit; } );
    I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted `remove_action` on it. What Maythan8 answered will work but it can be done with fewer functions. add_action('template_redirect', 'bt_maintenance_redirect'); function bt_maintenance_redirect () { if (is_page(4848) || current_user_can('administrator')) return; if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit; } You used `esc_url_raw` but this function is used for escaping url before DB storage, if your url is just for output use `esc_url`. Also better to use `wp_safe_redirect` if you are redirecting from and to the same host.
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "php, maintenance" }
    Iterate over get_post_meta() result I have WordPress code like below. function get_preselect_values() { $volunteers = get_post_meta($_POST['element_id'], "volunteers", false); $users = array(); foreach ($volunteers as $volunteer) { foreach ($volunteer as $volun) { $users = $volun['ID']; } } echo json_encode($users); die; } add_action('wp_ajax_get_preselect_values', 'get_preselect_values'); add_action('wp_ajax_nopriv_get_preselect_values', 'get_preselect_values'); I am getting only the **First** value. How can I get all values ?
    You're clobbering the value in the `$users` array with every iteration of the `foreach` loop. To add a new item to an array, you should use `$users[] = {...}`, not `$users = {...}`. function get_preselect_values() { $volunteers = get_post_meta($_POST['element_id'], "volunteers", false); $users = array(); foreach ($volunteers as $volunteer) { foreach ($volunteer as $volun) { $users[] = $volun['ID']; } } echo json_encode($users); die; } add_action('wp_ajax_get_preselect_values', 'get_preselect_values'); add_action('wp_ajax_nopriv_get_preselect_values', 'get_preselect_values');
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "get posts" }
    Will get_bloginfo('url') return URL with backslash? Based on my test, get_bloginfo('url') will not return backslash, so it will return URL like this: In this post What is difference between get_bloginfo('url') and get_site_url()?, it is said get_bloginfo('url') calls home_url(). And, in this post < it is said home_url() will return URL with backslash. So, I am confused. Anyway, I want to find a function to return URL **with** backslash.
    The Codex example for home_url() says you want `home_url( '/' )` to get the blog's URL with a trailing slash. Alternatively you could use `trailingslashit( home_url() )`. That may be safer if your site's home option somehow ends up stored with a trailing slash, since it looks like get_home_url() assumes it isn't, but that ought not happen.
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "urls" }
    How to cut off question mark in url with functions.php I use directive .htaccess <IfModule mod_rewrite.c> RewriteCond %{QUERY_STRING} !^$ RewriteCond %{QUERY_STRING} !(^|&)appId= RewriteCond %{QUERY_STRING} !(^|&)q= RewriteRule ^(.+?)\.html$ [L,R=301] </IfModule> The problem would be solved if this `RewriteCond %{QUERY_STRING} !^$` replace with this `RewriteCond %{THE_REQUEST} \?` But this directive does **not work** on the Litespeed server. That's for sure, I contacted the developers of this server. How to cut (redirect) to a link without a question mark **via** function.php? example: if open **website.com/post-name.html?** >>>redirect>>> **website.com/post-name.html** Sorry for my English.
    Try this, which uses the `parse_request` hook: (you can add other conditions, e.g. check whether `$wp->query_vars['name']` is not empty, if you want to) add_action( 'parse_request', 'wpse_400900_parse_request', 1 ); function wpse_400900_parse_request( $wp ) { // Redirect if the URL ends with a ? like if ( ! empty( $_SERVER['REQUEST_URI'] ) && ltrim( $_SERVER['REQUEST_URI'], '/' ) === "{$wp->request}?" ) { wp_redirect( home_url( $wp->request ) ); exit; } }
    stackexchange-wordpress
    { "answer_score": 1, "question_score": 0, "tags": "functions" }
    Edit post & page option does not display on latest wordpress I am not able to edit the WordPress default posts/pages from front-end. I have tried to deactivate all plugins, check/uncheck toolbar option(from profile) and also wp_footer() function in the file. But no luck any suggestion?
    I have found the issue and resolved with below code. function menu_shapespace_node_landearth($wp_admin_bar) { $wp_admin_bar->remove_menu('edit'); } //add_action('admin_bar_menu', 'menu_shapespace_node_landearth', 999);
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "posts, themes, pages, wp admin, links" }
    If Post Published Date or Modified Date is 1 Year or Older, Display Notice on Post Page I need a way to inform visitors if the post published date **or** modified date is older than 1 year and if so, display a message on the post page. I have added an code to my `content-single.php` file, but without the desired results in terms of checking against both published and updated time. **Example:** if (strtotime($post->post_date) < strtotime('-1 year')){ echo 'Old Post'; } else { echo 'Not Old Post'; } Any ideas as I'm in the dark here..
    Right now you're just checking for the post date. You'll need to check for 'post_modified' aswell. You can find the complete post-object here: < You can modify the check to look something like this: if (strtotime($post->post_date) < strtotime('-1 year') && strtorime($post->post_modified) < strtotime('-1 year')){ echo 'Old Post'; } else { echo 'Not Old Post'; } That should check for both.
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "php, posts, date, date time" }
    How to rename custom table name programatically in wordpress? in db there are custom table name like wp_wpdf_docs and want to change table name to wp_ccdm_docs as i am using $oldtable_name = $wpdb->prefix . "wpfd_docs"; $newtable_name = $wpdb->prefix . "ccdm_docs"; $rename= $wpdb->query("RENAME TABLE ".$oldtable_name ." TO " .$newtable_name); is it right process?
    Yes, you can use the `query` function to rename tables. global $wpdb; $oldTable = $wpdb->prefix . "wpfd_docs"; $newTable = $wpdb->prefix . "ccdm_docs"; $renameOk = $wpdb->query("RENAME TABLE " . $oldTable . " TO " . $newTable); if( $renameOk ) { echo 'All good'; }else{ echo 'Failed to rename table. Last DB error: ' . $wpdb->last_error; }
    stackexchange-wordpress
    { "answer_score": 0, "question_score": 0, "tags": "database" }
    read excel file in the dasboard programmatically To read a excel file inside wordpress, is there any function available, or we should build all using php?
    > To read a excel file inside wordpress, is there any function available WordPress does not provide functions for reading spreadsheets. PHP provides functions for reading CSV files via `fgetcsv` etc, but these are for `.csv` files. If you want to open an `xls` or `xlsx` file in code, and read its contents, you will need to find a PHP library for this, or implement the code yourself. A quick search of libraries on packagist reveals multiple pages of results for the word "excel". Keep in mind that what you are asking if not a WordPress question, but a generic PHP question, you don't have to limit yourself to just WordPress to solve this.
    stackexchange-wordpress
    { "answer_score": 2, "question_score": 0, "tags": "dashboard" }