text
stringlengths
12
210k
meta
dict
Q: Map WP Multisite blog.example.com to anotherdomain.com/blog? I have a WordPress Multisite installation at blog.example.com. I wish to serve it on somedomain.com/blog, I wish to know if this is possible. I'm aware of mapping blog.example.com to somedomain.com orabc.somedomain.com. I have Caddy server powering the WP multisite. Let me know how do I go about solving this problem. A: You can set up Caddy to reverse proxy requests to the Multisite installation: In your Caddyfile, add a reverse_proxy directive for the Multisite: somedomain.com/blog { reverse_proxy blog.example.com } This will forward all requests to somedomain.com/blog to the Multisite installation at blog.example.com. Next, update the WordPress Multisite configuration to use the new domain: In your WordPress database, go to the wp_blogs table and locate the row for your main site (usually with blog_id of 1). Change the domain and path values to somedomain.com and /blog, respectively. Also update the siteurl and home values in the wp_options table to https://somedomain.com/blog. steps required depending on your specific setup, such as updating permalinks, changing any hard-coded links in your content, and configuring SSL certificates.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AJAX multiple search boxes not merging with array merge this is a very frustrating problem. I have some search boxes for different feilds on my site. some are acf meta fields, another is for title, and another for a keyword taxonomy. But on the front end, only the first input box works (for title). If i use each query individually, it works fine. I am not clear why the merge is not working. I can add in more parameters into a single query, but for some reason using an array after the 's' => $title_q breaks it! In the ideal world, it would be best to have it all in one query, but I am struggling to see how to accomplish that. any help is appreciated! here is the input HTML: <!-- select report title --> <div class="dropdowndiv"> <label for ="Title">Title:</label> <input type="text" name="s" id="title" class="input_search" onkeyup="fetch();"> </div> <!-- select report author --> <div class="dropdowndiv"> <label for ="Title">Author:</label> <input type="text" name="t" id="author" class="input_search" onkeyup="fetch();"> </div> <!-- select report keyword --> <div class="dropdowndiv"> <label for ="Title">Keywords:</label> <input type="text" name="q" id="keywords" class="input_search" onkeyup="fetch();"> </div> <!-- select report year of publication --> <div class="dropdowndiv"> <label for ="Title">Year Of Publication:</label> <input type="text" name="r" id="year" class="input_search" onkeyup="fetch();"> </div> and the AJAX code: function fetch(){ jQuery.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', type: 'post', data: { action: 'data_fetch', keywords: jQuery('#keywords').val(), author: jQuery('#author').val(), title: jQuery('#title').val(), year: jQuery('#year').val(), }, success: function(data) { jQuery('#datafetch').html( data ); } }); } and finally the output PHP and queries: // the ajax function add_action('wp_ajax_data_fetch' , 'data_fetch'); add_action('wp_ajax_nopriv_data_fetch','data_fetch'); function data_fetch(){ extract($_POST); $author_q = $_POST["author"]; $title_q = $_POST["title"]; $keywords_q = $_POST["keywords"]; $year_q = $_POST["year"]; echo "search terms in php"; echo "<br/>"; echo $keywords_q; echo "<br/>"; echo $title_q; echo "<br/>"; echo $author_q; echo "<br/>"; echo $year_q; echo "<br/>"; $q1 = new WP_Query(array( 'post_type' => 'Library', 'fields' => 'ids', 'posts_per_page' => -1, 's' => $title_q, 'meta_key' => 'author', 'meta_value' => $author, )); $q2 = new WP_Query(array( 'post_type' => 'Library', 'posts_per_page' => -1, 'fields' => 'ids', 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'author', 'field' => 'slug', 'value' => $author_q, ), array( 'key' => 'year-of-publication', 'field' => 'slug', 'value' => $year_q, ) ), ) ); $q3 = new WP_Query(array( 'post_type' => 'Library', 'fields' => 'ids', 'tax_query' => array( array( 'taxonomy' => 'keywords', 'field' => 'slug', 'terms' => $keywords_q, ) ) ) ); $post_ids = array_unique( array_merge( $q1->posts, $q2->posts, $q3->posts ), SORT_REGULAR ); //$result = new WP_Query($q3); var_dump($post_ids); $wp_query_merged = new WP_Query(array( 'post_type' => 'Library', 'post__in' => $post_ids, 'orderby' => 'date', 'order' => 'DESC', )); while ( $q1->have_posts() ) : $q1->the_post(); ?> <p><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></p> <?php endwhile; echo '</div>'; wp_reset_postdata(); die(); }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress wp_mail not working on a few pages My code: if(isset($_GET['order_success']) && $_GET['order_success'] == 1){ $invoice_id = $_GET['invoice_id']; $to = $your_email; $subject = 'Payment Success'; $body = 'Thank you for purchasing our service! Your invoice ID is: '.$invoice_id.'. We appreciate your business and hope you enjoy your purchase. If you have any questions or concerns, please don\'t hesitate to contact us. Best regards, Alzeen Rent A Car'; $headers = array( 'Content-Type: text/html; charset=UTF-8', 'From: Your Name <[email protected]>', ); $headers = wp_parse_args($headers); $mail = mail($to, $subject, strip_tags($body), $headers); if ($mail) { echo '<span class="payment_success">Payment Success. Check your email for confirmation OR Save Invoice ID:<code>'.$_GET['invoice_id'].'</code>.</span>'; } else { echo 'An error occurred. Email not sent.'; } } It returns success but email is not receiving to me although I have installed the email logs plugin there too showing that the email is sent But not received. Can anyone help?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Disable duplicate WC product category URLs WC generates duplicate URLs when using category slugs. Example: demoshop.com/cat-1/product-a The same product can be accessed from any URL if slug "cat-1" is modified, e.g.: demoshop.com/modified/product-a will lead to a status code 200 as well. From a SEO perspective this is not preferrable and I would like to modify the behaviour as follows: If the product page is accessed via the correct url a 200 is sent. If the product page is accessed via any other url a 301 to the correct url is sent. If the product has muliple categories assigned, the primary one should be considered. Any hints how to realize that?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Have Wordpress Use a Different Database for users I have imported my users from Filemaker into a different table in Mysql. Can I have my user login to that database instead of the wp_users table. If so how do I connect it? Thanks in advance for your help
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I a custom search form by taxonomies? Im new in this of Wordpress, and I need to create a custom search form by Taxonomies, like a dropdown filter. Can u help me? Im just have the Searchform.php and this code for a Basic Search bar <?php <form role="search" method="get" class="form-inline my-2 my-lg-0" action="<?php echo esc_url( home_url('/')); ?>"> <input class="form-control mr-sm-2" type="search" placeholder="Buscar" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Buscar</button> </form>`
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iframe works for one C-Panel folder but not another I have successfully embeded an iframe in Wordpress (via Elementor) that displays a Unity3D game. The game is located in c-panel > file manager at: https://wordpress-staging.zafflower.com/SummersDay_020923/index.html. However, this is a staging site and I would like to have the Unity3D game in a different folder: https://public_html/SummersDay/index.html. When I copy or move the game to the new folder I get the error message: 'public_html’s server IP address could not be found.' I have tried changing the permission on the SummersDay folder from 755 to 750 which is the same as the permission on public_html, but that doesn't work. I have also tried making a new folder outside of public_html and giving it a 750 permission but that doesn't work either. My Wordpress site is hosted at HostGator. Is there something that HostGator has to do on their end, or can I do something to fix this? See iframe code below that works and iframe code that doesn't work. Any help will be much appreciated. Zaffer This iframe works: <iframe src="https://wordpress-staging.zafflower.com/SummersDay_020923/index.html" width="1200" height="900" frameborder="0" margin="0"></iframe> This iframe doesn't work: <iframe src="https://public_html/SummersDay/index.html" width="1200" height="900" frameborder="0" margin="0"></iframe> Addumdum: Here is a JPG of the file paths of the two instances of the game. I am using what I think are the correct paths. A: Thanks Jacob, I didn't realize that iframe could only reach an address that included a domain, not just a file path. I solved the problem by creating a subdirectory, games.zafflower.com, and installing a new WordPress site in that subdomain. Now this iframe code will correctly display my Unity3D game. Thanks! Zaffer <iframe src="https://games.zafflower.com/SummersDay/index.html" width="1200" height="900" frameborder="0" margin="0"></iframe>
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Customize margin between paragraphs using the Gutenberg Style editor I'm using the new Styles editor to customize the theme. I would like to change the spacing between the paragraphs of the page and single templates. Is that possible? A: This is possible if your theme supports full site editing. This is using Wordpress 6.1. * *From the admin, go to Appearance > Editor. *At the very top of the editor you will see the current template being edited. Click the little dropdown arrow next to that and then "Browse all Templates". *From the list of templates, click on Single or Page. *Click on the "styles" icon in the top right (looks like a half moon). *In the right hand panel, click on Blocks > Paragraph > Layout. *Click on the paperclip/link icon next to "padding" to allow you to set just vertical spacing without affecting horizontal spacing.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When trying to run build script with gutenberg (with SVG import) - Error: Plugin name should be specified I have a theme that is live and has some 10-20 custom gutenberg blocks, Those blocks sometime have svg imported to them like so import logo from './logo.svg' Today when I was trying to work and compile the theme getting an error in the SVGR plugin that comes with wp-scripts when ever I try to import any SVG to the block, This worked fine 2 days ago. Here is my package.json file. { "name": "some-project", "version": "1.0.0", "description": "A project for...", "main": "build/index.js", "scripts": { "build:scripts": "wp-scripts build", "start-build": "wp-scripts start", "lint:js": "wp-scripts lint-js", "lint:js:src": "wp-scripts lint-js ./src" }, "author": "", "license": "UNLICENSED", "repository": {}, "private": true, "devDependencies": { "@lottiefiles/lottie-player": "1.5.7", "@popperjs/core": "2.11.5", "@svgr/webpack": "^6.5.1", "@wordpress/scripts": "^24.2.0", "bootstrap": "5.1.3", "eslint": "^8.34.0", "eslint-config-airbnb": "^19.0.4", "eslint-plugin-import": "^2.27.5", "eslint-plugin-jsx-a11y": "^6.7.1", "eslint-plugin-react": "^7.32.2", "eslint-plugin-react-hooks": "^4.6.0", "flickity": "3.0.0", "jquery": "3.6.0", "lity": "2.4.1", "lodash": "4.17.21", "lodash.assign": "4.2.0", "prettier": "2.7.1", "typescript": "^4.7.4", "url-loader": "^4.1.1" }, "dependencies": { "build": "^0.1.4", "eslint-config-wordpress": "^2.0.0", "wp-scripts": "^0.0.1-security" } } Would love some help. My
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Looking for a way to insert PDF image preview in TinyMCE We're still using TinyMCE as our post editor. When Editors use the 'Add Media' button to select a PDF from the Media Library, they choose the thumbnail or medium size image from the Attachment Display Settings at bottom right. However, the result that gets pasted into the editor is simply a text link to the PDF but does not contain the jpg preview they expect. In other words, the result pasted into the editor is something like this: <a href="example.com/wp-content/uploads/mypdf.pdf">My PDF</a> But what they expect is something like this: <a href="example.com/wp-content/uploads/mypdf.pdf"><img class="thumbnail" src="example.com/wp-content/uploads/mypdf-thumbnail.jpg"/>My PDF</a> I have looked at the uploads folder and the various preview JPGs -are- being generated for each PDF. How can we enable that feature, ie. again, when the editor inserts a PDF from the media library, the preview img can be inserted along with an href to the PDF? Is there is a PHP function to enable this? Or is there a commonly used plug-in?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom shortcode with < in content I have created a custom shortcode for rendering text into tables. Without going into the details of the shortcode, I have initiated it with the following: [CardText type="tablelist" debug="ord"] This is a test|Less than:<8 [/CardText] For some reason WP doesn't seem to detect the content of the shortcode so that I can tidy up the < and replace it with &lt; (along with other disruptive characters). It renders the short code as: SOME TEST STUFF BELOW HERE Content was empty: debug cancelled This is a test|Less than:<8 [/CardText] END OF TEST STUFF I should add that if I replace the < manually it works perfectly. I seem to be going around in circles on this one - Thanks!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: slider wont load unless you scrolldown on mobile, slick.js carousel I use slick.js for my carousel. Everything is working fine on desktop but in my mobile I have this weird problem where the slider doesn't load correctly until I scrolldown. Have anyone here also experienced this, behavior. <script> $(document).ready(function() { $('.row-one-container .sliders-container').slick({ infinite: true, dots: true, arrows: true, responsive: [ { breakpoint: 500, settings:{ slidesToShow: 1, slidesToScroll: 1, infinite: true, } } ] }); </script> A: This behavior of the page is caused by the WP Rocker plugin you are using. With the active "Delay JavaScript Execution" option ("File Optimization" tab), all scripts on your website are loaded only after the user performs some action (e.g. will move the cursor). This applies to both the mobile and desktop versions. Excluding just jquery and slick.js from lazy load in WP Rocket settings should solve the problem.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: One item on menu is not clickable when it should be So basically all items of the menu should be clickable, and usually, I only have to add it to the menu and it will be clickable (doesn't matter if it's parent-child) but this specific category is not being clickable even though it has a link attached to it. Does anyone have an idea why this specific category is not being added as clickable? There's a parent category with a child item that also has sub-items. I want this child item (Surgical set) to be clickable too.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tab Element with Parent Tab & Child Tab I'm an Elementor user. I want to build this element in my page (see image below). How to Build this tab with parent tab & child tab? Also every parent tab/child tab has different content. Is there any widger or snippet that i have to use? Your answer really help me. Thank you. *The pink colored text is the active tab
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to delete "wp-block-group__inner-container" div from the gutenberg editor view? Currently I'm in the process of matching the editor style to the frontend, in order to facility page editing for unexperienced users. I have removed the "wp-block-group__inner-container" div from the front-end since it interferes with the HTML structure. The only problem is that this doesn't affect the block editor, and any styles containing grid or flex will not render correctly because of the added inner container. Is there a way to force the editor to not output those when using groups? I would really like the editor to match the final output of the page.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WordPress is adding pagination for all pages like www.example.com/page/123. How to remove that? I think WordPress is adding pagination for all pages like www.example.com/page/1234. In my case, it is adding for all pages not only for the blog page. How to remove the pagination for pages in WordPress?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Modal pop-up HTML code works on other sites or HTML viewers but not in the custom HTML block within a wordpress page? I'm not the best at coding, but I've managed to create this html code of a modal pop-up which includes CSS, Javascript, and html... it works in an html viewer or anywhere else except the wordpress custom html block. I have another version less complicated and it will work on wordpress (i.e the pop-up works and buttons press), but this version will not let me click the image to open the pop-up. I can't figure out if something in the code is preventing it or what. I've checked that the modal is executed properly within the code, all images have the correct id, CSS styles are okay. I've also checked within wordpress and cant find anything preventing this modal to not open when others could just as easily. I think it might be javascript related? Please help <style> /* The Modal (background) */ .modal { display: none; /* Hidden by default */ position: fixed; /* Stay in place */ z-index: 2147483647; /* Sit on top of everything */ left: 0; top: 0; width: 100%; /* Full width */ height: 100%; /* Full height */ overflow: auto; /* Enable scroll if needed */ background-color: rgba(0, 0, 0, 0.9); /* Black w/ opacity */ } /* Modal Content */ .modal-content { display: flex; justify-content: space-evenly; align-items: center; height: 100%; padding: 20px; text-align: center; } /* Image */ .modal-image { width: 500px; height: 500px; } /* How To Box */ .how-to { display: flex; flex-direction: column; justify-content: space-evenly; align-items: center; padding: 20px; background-color: #eee; cursor: pointer; margin: 30; } /* Preview */ .preview, .iframe-class { display: none; position: center; } a:hover .iframe-class { display: block; position: center; } /* The Close Button */ .close { position: absolute; bottom: 20px; margin-left: 50%; font-weight: bold; transition: 0.3s; width: 200px; background-color: black; color: white; height: 50px; font-size: 20px; } .option-box { text-decoration: underline; } .close:hover, .close:focus { color: #bbb; text-decoration: none; cursor: pointer; } .preview-container { background-color: white; width: 800px; height: 500px; } .preview-title { text-align: center; } .options-container { float: right; width: 50%; position: absolute; bottom: 130px; margin-left: 36%; } .options-container button { padding: 20px; margin-right: 5%; margin-left: 5%; width: 175px; } .option.selected { background-color: gray; color: white; } iframe { display: block; width: 99%; height: 85%; } .disabled { display: none; } .arrows-container { text-align: center; margin-top: 15px; } @media screen and (max-width: 800px) { .modal-content { display: block; } iframe { width: 98%; } .preview-container { width: 100%; } .modal-image { width: 80%; margin-bottom: 10px; } .close { bottom: -25%; margin-left: 40%; } .options-container button { padding: 1%; } .options-container { margin-top: 25px; display: inline-flex; float: none; width: unset; position: unset; bottom: 0; margin-left: 0; } } </style> <!-- The Image --> <img id="myImg" src="https://sites.gatech.edu/flourishingcommunities/files/2023/01/BuildingEnvelope_TipCards3.jpg" width="300" height="300" onclick="openModal();" /> <!-- The Modal --> <div id="myModal" class="modal"> <div class="modal-content"> <div> <img class="modal-image" id="img01" src="https://sites.gatech.edu/flourishingcommunities/files/2023/01/BuildingEnvelope_TipCards3.jpg" /> </div> <div> <div class="preview-container"> <div class="preview-box" id="1"> <div class="preview-title"> Preview: <a href="https://sites.gatech.edu/flourishingcommunities/files/2023/01/01-TE-How-To-Weatherstrip-Doors.pdf">How-To-Weatherstrip-Doors-PDF 1</a> </div> <iframe src="https://sites.gatech.edu/flourishingcommunities/files/2023/01/01-TE-How-To-Weatherstrip-Doors.pdf" width="600px" height="300px"> </iframe> </div> <div class="preview-box disabled" id="2"> <div class="sub-box"> <div class="preview-title"> Preview: <a href="https://sites.gatech.edu/flourishingcommunities/files/2023/01/01-TE-How-To-Weatherstrip-Doors.pdf">How-To-Weatherstrip-Doors-PDF 2.1 </a> </div> <iframe src="https://sites.gatech.edu/flourishingcommunities/files/2023/01/01-TE-How-To-Weatherstrip-Doors.pdf" width="600px" height="300px"> </iframe> </div> <div class="sub-box disabled"> <div class="preview-title"> Preview: <a href="https://sites.gatech.edu/flourishingcommunities/files/2023/01/01-TE-How-To-Weatherstrip-Doors.pdf">How-To-Weatherstrip-Doors-PDF 2.2 </a> </div> <iframe src="https://sites.gatech.edu/flourishingcommunities/files/2023/01/01-TE-How-To-Weatherstrip-Doors.pdf" width="600px" height="300px"> </iframe> </div> <div class="sub-box disabled"> <div class="preview-title"> Preview: <a href="https://sites.gatech.edu/flourishingcommunities/files/2023/01/01-TE-How-To-Weatherstrip-Doors.pdf">How-To-Weatherstrip-Doors-PDF 2.3 </a> </div> <iframe src="https://sites.gatech.edu/flourishingcommunities/files/2023/01/01-TE-How-To-Weatherstrip-Doors.pdf" width="600px" height="300px"> </iframe> </div> <div class="arrows-container"> <button onclick="previousSubBox()">&#60;&#60;</button> <button onclick="nextSubBox()">>></button> </div> </div> <div class="preview-box disabled" id="3"> <div class="preview-title"> Preview: <a href="https://sites.gatech.edu/flourishingcommunities/files/2023/01/01-TE-How-To-Weatherstrip-Doors.pdf">How-To-Weatherstrip-Doors-PDF 3</a> </div> <iframe src="https://sites.gatech.edu/flourishingcommunities/files/2023/01/01-TE-How-To-Weatherstrip-Doors.pdf" width="600px" height="300px"> </iframe> </div> </div> </div> <div class="options-container"> <button class="option selected" onclick="activatePreview(this, 1)"> Finanacial incentive's </button> <button class="option" onclick="activatePreview(this, 2)"> How To's </button> <button class="option" onclick="activatePreview(this, 3)"> Option 3 </button> </div> </div> <button class="close" onclick="closeModal()">Close</button> </div> <script> /* JAVASCRIPT */ var modal = document.getElementById("myModal"); function openModal() { var img = document.getElementById("myImg"); var modalImg = document.getElementById("img01"); modal.style.display = "block"; modalImg.src = img.src; } window.onclick = function (event) { if (event.target == modal) { modal.style.display = "none"; } if (event.target.className === "how-to") { var previews = event.target.getElementsByClassName("preview"); for (var i = 0; i < previews.length; i++) { previews[i].style.display = "block"; } } }; function closeModal() { hidePreviews(); modal.style.display = "none"; } function activatePreview(target, id) { deactivatePreviews(); target.classList.add("selected"); var previewBoxes = document.getElementsByClassName("preview-box"); for (var i = 0; i < previewBoxes.length; i++) { if (previewBoxes[i].id == id) previewBoxes[i].classList.remove("disabled"); else previewBoxes[i].classList.add("disabled"); } } function deactivatePreviews() { var buttons = document.getElementsByClassName("option"); for (var i = 0; i < buttons.length; i++) { buttons[i].classList.remove("selected"); } } function nextSubBox() { var subBoxes = document.getElementsByClassName("sub-box"); for (var i = 0; i < subBoxes.length; i++) { if (subBoxes[i].className == "sub-box" && i + 1 < subBoxes.length) { subBoxes[i].classList.add("disabled"); subBoxes[i + 1].classList.remove("disabled"); return; } } } function previousSubBox() { var subBoxes = document.getElementsByClassName("sub-box"); for (var i = 0; i < subBoxes.length; i++) { if (subBoxes[i].className == "sub-box" && i - 1 >= 0) { subBoxes[i].classList.add("disabled"); subBoxes[i - 1].classList.remove("disabled"); return; } } } function hidePreviews() { var previews = document.getElementsByClassName("preview"); for (var i = 0; i < previews.length; i++) { previews[i].style.display = "none"; } } </script> </div> </div> ''' A: There are a couple of issues with what you are trying to do. See this for reference: Wordpress support for Custom HTML blocks First, you cannot reliably add JS code directly into any block, which is intended only for HTML and text. While the script tags may technically be HTML, your JS code certainly is not HTML or text. In the supplied link you see the list of supported tags and script isn't one of them. My suggestion would be to create a shortcode for this. Second, for security reasons an iframe is only allowed on plug-in enabled sites. According to this, your site would need to be Business, Commerce or Enterprise. Plugin Enabled Sites Sorry, there isn't a quick fix.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AJAX WP_Query's order and orderby parameters not working TL;DR SUMMARY OF PROBLEM AJAX will not use the proper order and orderby parameters given, and instead sorts post by menu_order (posts section doesn't even have post attributes set as true). PROBLEM OVERVIEW I am having a perplexing problem. I am in the process of creating a filtering system using AJAX and WordPress where the user will be able to filter through the posts by category and alter the order and orderby parameters to sort the posts by either ascending/descending dates and titles. I have the category filtering working, but the order and orderby parameters will not work. Since the filtering works, I will only display the section correlated to the order and orderby parameters. Important HTML: This section is a drop down menu where the user can choose how they want the posts to be sorted. <div class="laschf-sort"> <select name="sort" id="archive-sort"> <option hidden disabled selected value="default"> Sort by </option> <option value="date-desc">Date (Oldest - Newest)</option> <option value="date-asc">Date (Newest - Oldest)</option> <option value="title-asc">Title (A - Z)</option> <option value="title-desc">Title (Z - A)</option> </select> </div> On change, the value is passed through AJAX and determines the parameters that are used in the Query (following is the jQuery/AJAX): $('#archive-sort').on('change', function() { filterNew = 1; var filterInput = $('#archive-filter').val(); var sortInput = $('#archive-sort').val(); var sortby = ''; var sort = ''; if(sortInput == 'date-asc') { sortby = 'date'; sort = 'ASC'; }else if(sortInput == 'date-desc') { sortby = 'date'; sort = 'DESC'; }else if(sortInput == 'title-asc') { sortby = 'title'; sort = 'ASC'; }else if(sortInput == 'title-desc') { sortby = 'title'; sort = 'DESC'; }else{ sortby = 'date'; sort = 'DESC'; } console.log(filterInput); $.ajax({ type: 'POST', url: ajax_url, dataType: 'json', data: { action: 'articles_filter_sort', paged: filterNew, cat: filterInput, sortby: sortby, sort: sort, }, success: function (res) { console.log(res.query); $('.lasca-wrapper').empty(); $('.lasca-read-more-wrap').empty(); $('.lasca-wrapper').append(res.html); $('.lasca-read-more-wrap').append(res.readMore); if(filterNew >= res.max) { $('#aa-filter-load-btn').hide(); } } }); }); As you can see, the values are taken from the drop down (and the filter is also taken from the other drop down select), then passed to a function (below), and upon success, the div which contains the posts are emptied and the new html is appended to the div. The function (PHP): /** * SORT AND FILTER FUNCTION */ function articles_filter_sort() { $order = $_POST['sort']; $orderby = $_POST['sortby']; if($_POST['cat'] != null && $_POST['cat'] != 'all') { $args = [ 'post_type' => 'post', 'posts_per_page' => '9', 'status' => 'publish', 'orderby' => $orderby, 'order' => $order, 'paged' => $_POST['paged'], 'cat' => $_POST['cat'], //'suppress_filters' => true, ]; }else{ $args = [ 'post_type' => 'post', 'posts_per_page' => '9', 'status' => 'publish', 'orderby' => $orderby, 'order' => $order, 'paged' => $_POST['paged'], //'suppress_filters' => true, ]; } //remove_all_filters('posts_orderby'); $filter_articles = new WP_Query($args); $response = ''; $readMore = ''; $max_pages = $filter_articles->max_num_pages; if($filter_articles->have_posts()) { while($filter_articles->have_posts()) : $filter_articles->the_post(); $response .= '<div class="archive-article-card"> <div class="aac-cat-share"> <div class="aac-category"> <span>' . get_the_category()[0]->name . '</span> </div> <button class="multi-btn"> <i class="share-icon fa-light fa-share-nodes"></i> <ul> <li> <a class="share-btn share-twitter" href="https://twitter.com/intent/tweet?text=' . rawurlencode(get_the_title()). ':%20' . get_permalink() . '"><div class="twitter-btn share-btn"><i class="fa-brands fa-twitter"></i></div></a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> </li> <li> <a class="share-btn share-fb" href="https://www.facebook.com/sharer/sharer.php?u=' . get_permalink() . '" title="Share on Facebook" target="_blank"><div class="fb-btn share-btn"><i class="fa-brands fa-square-facebook"></i></div></a> </li> <li> <a class="share-btn share-linkedin" href="https://linkedin.com/shareArticle?url=' . get_permalink() . '" target="_blank"><div class="linkedin-btn share-btn"><i class="fa-brands fa-linkedin"></i></div></a> </li> </ul> </button> </div> <div class="aac-content"> <div class="aacc-date">' . get_the_date('d.m.Y') . '</div> <div class="aacc-title">' . get_the_title() . '</div> <div class="aacc-excerpt">' . bl_get_excerpt() . '</div> </div> <div class="aac-post-read-more-wrap"> <div class="aacprm-button"> <a href="' . get_post_permalink() .'"> <button>View Details <span>&#10230;</span></button> </a> </div> </div> </div>'; endwhile; $readMore .= '<button id="aa-filter-load-btn">View More</button>'; }else{ $response .= 'No Posts Found'; } $result = [ 'max' => $max_pages, 'html' => $response, 'readMore' => $readMore, 'query' => $filter_articles->query, 'orderby' => $orderby, 'order' => $order, 'args' => $args ]; echo json_encode($result); exit; } add_action('wp_ajax_articles_filter_sort', 'articles_filter_sort'); add_action('wp_ajax_nopriv_articles_filter_sort', 'articles_filter_sort'); So as you can see, the function checks to see if there is a filter and determines which argument to use for the Query. The Query then determines the number of pages in the search (this is used for the read more button), and generates the posts using the response html. This response will also send the html for the read more button as well. After the html is generated, the function then collects all the results that is sent back to AJAX to be appended to the html. EXPECTED RESULTS I expect this to work. This function is used for the filter AJAX as well, and works perfectly. The sorting functionality should be sending the order and orderby arguments and it should be used in the query. What Is Happening As you can see, I actually output the query in the results and I have it console.log()'d within the AJAX success. When change the value in the drop down, I can actually see the query used by the AJAX, and it indicates that it is (should be) using the correct parameters (as in I can see "orderby" => "date" and "order "DESC" if I choose "Sort by Date Oldest to Newest" within the Query). However, if I output queryparams as well as the query, the queryparams indicates that orderby is menu_order for every sort, despite the query not using it. What I've Done So as you can see, I have done troubleshooting to figure out what is happening behind the scenes. And in my research, the only thing I could find is that AJAX uses admin filtering which is causing the menu_order to be used instead of the proper parameters. I have tried used 'suppress_filters' => true in the argument, but that did not solve the problem. I have also tried running the function remove_all_filters('posts_orderby'); before the Query call, and that also did not work. Question Does anyone know a way for me to ensure the proper parameters are being used in the output instead of menu_order? A: Found the solution in case anyone is having the same problem. Before the Query call I ran: remove_all_actions('pre_get_posts');
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove login link from Reset Password-screen I haven't been able to find anything useful regarding removing or hiding the "Login" link from the Reset Password screen and the screen after succesfully choosing a new password. I'm using a custom login-form made with GravityForms and would like to stay away from the built-in Wordpress forms as much as possible, but I can't make a custom reset. The built-in forms can work if I can remove the links to login, so the users aren't able to login any where else but the one I've made with GravityForms. Thanks in advance!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ACF in radio button cf7 Good morning, I hope I am in the right place. A customer has asked me to create contact forms with radio choices that have values taken from ACF (Advanced Custom Field) I enclose a screnn and write an example in red are the ACFs Rental 12 Months [Radio 1] 96000 km at 2850€. [Radio 2] 120000 km at 2900€. [Radio 3] 150000 km at 3000€. is this possible?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: post_row_actions filter from parent theme not executing in child theme In functions.php for a theme I include a file that adds functionality to allow the easy duplication of posts - the include file contains the code from this (very useful) webpage. I include it like this: include "inc/duplicate-posts.php"; The include contains all the functions from that page, plus the add_filter line that hooks it all up, and it works fine in that theme. However, I also use this theme in another site as the parent to a child theme. It doesn't add the post duplication functionality here, and I can't see why. The file is still being included (from the parent theme, via its functions.php), if I add an echo 'lkaslasjd'; line that outputs ok. But the function that's supposed to be connected via post_row_actions doesn't seem to execute, and the extra functionality isn't added. This is probably a simple misunderstanding on my part, but can anyone help me understand what I need to do to get this to work? Update: Code works fine, error was all mine A: There has been a major misunderstanding of child themes. Parent and child themes are a WordPress feature, not a PHP feature, and include is a PHP directive, not a WordPress function. To make the distinction and reason clearer child themes don't inherit a parents "files" they inherit the parents "templates". So include "inc/duplicate-posts.php"; will always be relative to the current file that's calling it, not the root of the current theme, and it will never look in the parent theme. Instead, it looks like there's been a misunderstanding about how templates are meant to be loaded in WordPress. This loads a template file in your theme: get_template_part( 'template', 'file' ); It will load the first file in this list that it can find: * *template-file.php in the child theme *template-file.php in the parent theme *template.php in the child theme *template.php in the parent theme Always use get_template_part for templates, files that render HTML. These can be overloaded/replaced via child themes. Never use get_template_part for library files or files that define classes and functions, e.g. your includes folder. Always use include/include_once/require/require_once for arbitrary PHP files that declare hooks/functions/classes, libraries etc.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add links to different language versions of WordPress How to create link for current page but in different subdomain (translation) in WP? For example on https://domain.com/test_page link to https://uk.domain.com/test_page/ and https://pl.domain.com/test_page/
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use shortcode to get the second to newest post? I've done considerable research, and tried multiple solutions to my task, and currently have found a way but i know it is not the best, so hoping for input to do this better. The task I am using Shortcode in Menus plugin combined with custom shortcodes to display between one and three of the latest blog posts in my site's main menu. . For each menu link, it's a menu item added using that plugin, with the title and link each set via a different shortcode: The way it will work, is I have three menu items added in WordPress menu editor, each using a shortcode to pull one post - one pulls the most recent, one pulls the next most recent, and so on. I currently have 2 shortcodes - one pulling title, one pulling permalink. (This question is not technically about it, but I think i could do it with one shortcode, and $atts to grab title or link, so feel free to chime on that too). The issue with my code This pulls the latestlink ok, but to pull the second most recent, i tried using offest - which is commented out below, as it was pulling the most recent - but setting offset to 2, or 3, does not do anything. What does work, is setting 'posts_per_page' => 3, 'offest' => 3,. add_shortcode('latest_blog_post_link', 'get_latest_blog_post_link'); function get_latest_blog_post_link($atts, $content = null) { $args = array( 'posts_per_page' => 1, // 'offest' => 1, 'cat' => '38, 21, 30, 39, 10, 8, 26, 20, 22, 18, 9, 24, 11' // replace this number with your category's ID ); $posts = get_posts($args); foreach($posts as $post) { $latest_post = get_permalink($post); } return $latest_post; } So my question is, is there a better way to do this? Do I have to set posts_per_page to a value higher than 1 for offset to work?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress menu empty of items Intermittently, every few weeks, the menu appears empty of items. I have not determined a pattern or cause. The menu no longer appears on the website in this state. This fix is for me to add an item and save menu. Then all the items reappear. As an example, I add this "Policies" page and save: Then the original menu appears again: I then remove the page I added, save again and the original menu appears and everything works as before. Has anyone experienced this before?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress rewrite rule - not able to access second and third parameters I have a rewrite rule; add_rewrite_rule( 'jobs/search/([^/]+)/state/([^/]+)/position/([^/]+)/?$', 'index.php?post_type=job&search=$matches[1]&state=$matches[2]&position=$matches[3]', 'top' ); It correctly loads the jobs page and I am able to access the search query var, however trying to get state and position returns blank. Example URL: https://website.com/jobs/search/chef/state/nsw/position/full-time/ Current result: Expected result: What am I missing here?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Slug is already taken - how do I find the original item I have a similar problem to this post: Slug Taken, Cant Find Which Page I'm needing to create a page with slug /harvest but this is apparently already taken as WP insists my slug must be /harvest-2. This is a large complex site with a long history (I'm updating it) and 'harvest' is a common term. * *There is no page or post in trash *No taxonomy or CPT called Harvest *I've run the function given in the post above. Nothing shows except my new page and other items with terms including 'harvest' (eg 'harvesters' etc...). *No media items or menu items are currently called 'harvest'. There was but I have changed it. *I've installed 'Slugs Manager' plugin and removed any legacy slugs A: I found the answer. I had previously located a media item with /harvest and fixed the slug but its NAME was still 'harvest'. I couldn't lfind where to change this so deleted and re-uploaded it. Fixed.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Theme Widget Area Defaults In my custom theme's function.php file, I have created a widget area: function my_footer_widget_area() { $args = array( 'id' => 'footer_widget_area', 'class' => 'my_widget_footer', 'name' => __('Footer Widget Area', 'mynamespace'), 'description' => __('Widgets for the footer. The widget title will appear above the widget content. Leave the title blank to only display widget content.', 'mynamespace'), ); register_sidebar($args); } Which is activated with add_action('widgets_init', 'my_footer_widget_area'); The theme's sidebar.php file contains if (is_active_sidebar('footer_widget_area')): ?> <div id="tertiary" class="footer-container" role="complementary"> <div class="footer-inner"> <div class="widget-area"> <?php dynamic_sidebar('footer_widget_area');?> </div><!-- .widget-area --> </div><!-- .footer-inner --> </div><!-- #tertiary --> <?php else: ?> <!-- Time to add some widgets! --> <div id="tertiary" class="footer-container" role="complementary"> <div class="footer-inner"> <div class="widget-area"> <!-- <p>footer sidebar - not active</p> --> </div> </div> </div> <?php endif; When the theme is activated, the widget area is active, but the widget area contains widgets. How do I create the widget area with no widgets in that widget area? Are there default widgets assigned to a created widget area? If so, how do I disable those default widgets?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get Comment Text via REST API Added Note that this process is in a WP plugin, using thw WP API, so I believe this is appropriate for this SO and should not be closed. The following REST call is used to get a specific comment: var comment_id = 239; response = wp.apiRequest( { // ajax post to set up comment redact meta value path: 'wp/v2/comments/' + comment_id , method: 'POST', data: thedata } ); This returns a JSON object, and the next step is to get the comment text from the JSON object, which contains these values (not complete response, and sanitized): { "id": 239, "post": 424, "parent": 0, "author": 1, "author_name": "username", "author_url": "", "date": "2023-02-20T12:43:02", "date_gmt": "2023-02-20T20:43:02", "content": { "rendered": "<div class=\"comment_text\"><p>here is a comment</p>\n</div>" }, "link": "https://example.com/my-test-post/#comment-239", "status": "approved", "type": "comment", } My problem is I can't figure out how to get the 'rendered' value. I have tried this: response_array = JSON.parse(response.responseText); but get an error: JSON.parse: unexpected character at line 1 column 1 of the JSON data Still learning JSON, and have done many searches to now avail. What JS code will get me the comment text out of the response object? A: A brief introduction and what does wp.apiRequest() return wp.apiRequest() is one of the three JavaScript API written by WordPress (the other two JavaScript APIs are the Backbone JavaScript Client and wp.apiFetch()), which we can use to communicate with the WordPress REST API, and as for wp.apiRequest(), it uses jQuery.ajax() which returns a jqXHR object that implements the Promise interface, giving it all the properties, methods such as .then(), and behavior of a Promise. See https://api.jquery.com/Types/#Promise The issue with your code Originally, I thought the AJAX request had not been resolved (or not yet complete) and thus response.responseText was an undefined, instead of a JSON-encoded string. Demonstration of the issue: const response = wp.apiRequest( { ... } ); // Note: That `response` is a jqXHR object. // At this point, responseText is still an undefined. console.log( 'before calling .then()', response.responseText, response ); response.then( ( comment, status, jqXHR ) => { // At this point, responseText is filled and it's a proper JSON-encoded string. console.log( comment, jqXHR.responseText, response.responseText ); } ); // At this point, responseText is also still an undefined. console.log( 'after calling .then()', response.responseText, response ); But then after reading your answer or checking your code there, if you actually did something like this: .then( function( response ) { // Parse the JSON response into a JavaScript object. response_array = JSON.parse(response.responseText); } ) Then that response.responseText was also (likely) an undefined, because the REST API would not add such property by default, and you should have actually read it from the third parameter, i.e. the jqXHR object above. But you don't have to manually parse the response text into an object, because the first parameter is already an object representation of the response text. How to properly get the comment text (the value of content.rendered) and other data You can use .then() or these jQuery-specific methods: .done() (and .always()). There's already an example above, which uses .then(), but here's another example: wp.apiRequest( { path: 'wp/v2/comments/' + comment_id, method: 'POST', data: thedata } ).then( function ( comment ) { console.log( comment.content.rendered ); } ); If you want wp.apiRequest() to return the comment object instead of jqXHR, then you can use await and async. Here's an example which uses IIFE (Immediately Invoked Function Expression): async function editComment( comment_id, thedata ) { const comment = await wp.apiRequest( { path: 'wp/v2/comments/' + comment_id, method: 'POST', data: thedata } ); const commentText = comment?.content?.rendered; console.log( commentText ); // This is logged first. return comment; } // This is an IIFE. ( async () => { const comment = await editComment( 123, { content: 'new content here' } ); console.log( 'after', comment ); // This is logged after the one above. } )(); A: I will mark @SallyCJ's request as correct, but I figured out the answer prior to reading hers (which is similar to what I used successfully), and wanted to supplement her answer with the code that I used to fix the issue. Note that the answer was provided with ChatGPT, and I verified it worked properly. Here's the relevant code, similar to what SallyCJ posted: response = wp.apiRequest( { path: 'wp/v2/comments/' + comment_id, method: 'POST', data: thedata, fields: 'content', } ).then( function( response ) { // Parse the JSON response into a JavaScript object //console.log(response); const contentRendered = response.content.rendered; console.log(contentRendered); } ).catch( function( error ) { console.error( error ); } ); My issue was trying to use JSON.parse() on the response, to parse the response into a JS JSON object. But it already was the correct type of object to use. Trying to parse it resulted in the error 'unexpected character at line 1 column 1 of the JSON data'. Note that I had done hours of searching here and other places to get an answer, and the ChatGPT gave me the correct answer. I am aware that ChatGPT answers may not be valid or accepted here, but I tested it's answer and it worked properly.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamically count the number of custom post types associated to a custom taxonomy I have two custom post types, "participants" and "reports". Both of them are associated with the custom taxonomy "year". So in the post "report 1" that is flagged under "2023" taxonomy I want to show the number of "participants" that are flagged under the same taxonomy (2023). The "Report 2" is flagged under "2022" taxonomy and it must show the number of "participants" that are flagged under the same taxonomy (2022). And so on. Whatever I find online, it's always hard coded. But I need it to be dynamic. Any ideas? A: You have to get them with WP_Query. Creat an array then get the number of posts from found_posts function.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get all scripts and styles from the header. Including those added by plugins? Good afternoon! wp_styles() or global $wp_styles gets styles from the header only of WordPress itself. And how to get absolutely all styles from the header, including those added by plugins? I need to get this style added by the WooCommerce plugin: <link rel="stylesheet" id="jquery-ui-style-css" href="/wp-content/plugins/woocommerce/assets/css/jquery-ui/jquery-ui.min.css?ver=7.3.0" media="all"> But the function wp_styles() doesn't see him.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to hide button with CSS class? I have two filter buttons appearing on my new version of HUSKY plugin. One button is from old WOOF filter plugin with the name "Filter" on it, the other also named FILTER. And the other from new HUSKY plugin (the new version of WOOF). I'm used old WOOF plugin and recently bought new. And although I deleted the old version, for some reason an additional button appears that does not function. How can i hide one button with extra css class ? With the code below all elements remains hidden. button.button { visibility: hidden; } button.button.woof_submit_search_form_container { visibility: visible; } Thank you !
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nav menù doesn't display selected pages I've included Elementor inside my custom plugin and now I'm creating my wp site layout. I've noticed that my nav menu will show all the pages I have created for my website, but from the settings I've only included three pages to show. This is the code I have in my header.php file wp_head(); wp_nav_menu( [ 'theme_location' => 'header-menu', 'menu_id' => 'header-menu', 'container' => 'nav', ] ); Is there something I've missed in the code or I need to change some setting from the menù page in wp dashboard?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make WP in two languages (e.g. English & Bengali) without plugins I want to make a WordPress website in 2 languages (e.g. English & Bengali) without plugins. Currently my site is plain html with 2 folders. English pages in one folder and Bengali pages in another folder. How do I do it on WordPress without plugin? How to do it theme page/post? A: A way my agency has chosen to implement it in the past is through subdomains. We created the entirety of our English site as you would normally in WordPress on mydomain.com, used the Duplicator plugin to clone the site to spanish.mydomain.com, and then changed all the text on the new site. And as @MarkKaplun recommends, a multisite setup would be appropriate here as well, though slightly more complex. It lets you keep the same WordPress core for both sites, but different content. An option is to use a plugin like WPML (which is generally considered the best plugin to use if you ended up wanting to go that route). However, there are issues as pointed out by @MarkKaplun such as the integration with other plugins and WPML assuming all content should be the same.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a transient that persists the data for the whole duration of the expiration, even when object cache is enabled? Anyone recommends an alternative to set_transient that persists the data for the whole duration of the expiration even when object cache is enabled? Example: * *List item *Set a long-duration transient set_transient('foo', 'bar', WEEK_IN_SECONDS); *Site is using object cache, so this is saved in memory *I don't know internals of Redis, but memory cache is cleared for some reason: * *Redis rotates cache based on the eviction policy *Server reboots *O.S-level memory management frees up memory *etc? Now that transient expired before 1 week. In a scenario such as this, how can I create a value that is able to persist for a longer period? A: I eventually used a combination of update_option and WP Cron: // Create the option. update_option('foo', 'bar', false); /** * Schedule it to be deleted one week from now. * * @param int Expiration timestamp * @param string Hook that will be invoked * @param string Params to send to the hook callback */ wp_schedule_single_event( time() + WEEK_IN_SECONDS, 'expire_option', [ 'foo' ] ); // Register the hook. add_action( 'expire_option', 'expire_option_callback', 10, 1 ); // This will be called by WP Cron when we want to "expire" the option, one week after its creation. function expire_option_callback( $option_name ) { delete_option( $option_name ); } The only drawback is that the option won't be expired if WP Cron is not working in the site. If this is unnaceptable, you'll need a more robust solution mimicking how transients are saved and expired in the DB.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: plugin translation *.mo file not getting loaded for custom post I'm encountering a weird behavior with the translation for a custom plugin I've made for a customer. The translation files are in the plugin languages folder and I load them with load_plugin_textdomain. In the plugin page inside wp-admin, I see the translation: In the front-end pages, I see the translation: In the custom post page in wp-admin not: If I move the *.mo file in the wp-content/languages/plugin folder, it works fine. why? is it a normal behavior? Am I doing something wrong? Here's the code: Pluginname: interzero_team.php in folder interzero_team /* * Text Domain: interzero_team * Domain Path: /languages */ /** * create custom post type for the staff members */ function interzero_team_create_cpost_staff(){ $labels = array( 'name' => esc_html__( 'Team members', 'interzero_team' ), 'singular_name' => esc_html__( 'Team member', 'interzero_team' ), 'add_new' => esc_html__( 'Add a new member', 'interzero_team' ), 'add_new_item' => esc_html__( 'Add a new member', 'interzero_team' ), 'edit_item' => esc_html__( 'Edit team member', 'interzero_team' ), 'new_item' => esc_html__( 'New team member', 'interzero_team' ), 'all_items' => esc_html__( 'Show the team', 'interzero_team' ), 'view_item' => esc_html__( 'View a member', 'interzero_team' ), 'search_items' => esc_html__( 'Search for a member', 'interzero_team' ), 'not_found' => esc_html__( 'No member found', 'interzero_team' ), 'not_found_in_trash' => esc_html__( 'No member found in the Trash', 'interzero_team' ), 'parent_item_colon' => esc_html__( 'Parent', 'interzero_team' ), 'menu_name' => esc_html__( 'Team', 'interzero_team' ) ); $args = array( 'labels' => $labels, 'description' => 'Team members', 'public' => true, 'publicly_queryable' => true, 'hierarchical' => false, 'menu_position' => 10, 'menu_icon' => 'dashicons-groups', 'show_in_rest' => false, 'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields', 'excerpt', 'post-formats' ), 'has_archive' => true, 'rewrite' => array( 'with_front' => false, 'slug' => 'staff' ), 'query_var' => true, 'taxonomies' => array('department') ); register_post_type( 'team-member', $args ); } add_action( 'init' , 'interzero_team_create_cpost_staff', 0); /** * localize */ function interzero_team_load_plugin_textdomain() { load_plugin_textdomain( 'interzero_team', false, basename( __DIR__ ) . '/languages/' ); } add_action( 'init', 'interzero_team_load_plugin_textdomain' ); A: I solved it. It was a priority problem: The add_action( 'init' , 'interzero_team_create_cpost_staff', 0); had a priority of 0, so it was loaded before the translations where available. ciao
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is my custom email notification after purchase not sending? I'm trying to send an email to a specific address (the admin) but online if a customer purchases one of four specific products. I'm using this code in my functions.php in my plugin for the page. But no email is received. Other emails are being sent on the page. Am I missing something? The code looks fine to me. add_filter( 'woocommerce_email_recipient_new_order', 'conditional_recipient_new_email_notification', 15, 2 ); function conditional_recipient_new_email_notification( $recipient, $order ) { if ( ! is_a( $order, 'WC_Order' ) ) { return $recipient; } $targeted_ids = array(3481, 3480, 3466, 3479); // products ids $addr_email = '[email protected]'; // email // Loop through orders items foreach ($order->get_items() as $item_id => $item ) { if ( in_array($item->get_variation_id(), $targeted_ids) || in_array($item->get_product_id(), $targeted_ids) ) { $recipient = $addr_email; break; // Found and added – We stop the loop } } return $recipient; } A: Check if the email is not going to spam or junk folder. Sometimes, emails from automated systems can be classified as spam by email providers. Make sure that the email address '[email protected]' is correct and working. Verify that the four product IDs in the $targeted_ids array are correct and match the IDs of the products you want to trigger the email. Make sure that the code is executing by adding some debug statements like "echo 'Code is executing';" at the start of the function to see if it's being executed. Check if the email sending functionality is working on the website by trying to send a test email using a plugin like WP Mail SMTP. Finally, you can also try using a different email address for the recipient to check if the issue is specific to the email address '[email protected]'.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to update or change internal default urls in wordpress? I am using inClinic theme in wordpress and have changed the permalink from setting as per my need. But there is Doctor link whach is having plugin name in the url and I am not able to find any setting to change it. My url is for example https://mydomainurl.com/cmsms_doctor/dr-abc-example/ and i want this to look like https://mydomainurl.com/dr-abc-example/ or https://mydomainurl.com/doctor/dr-abc-example/ I have checked all the settings but getting nothing Wordpress is all about setting. I tried to change the permalink but I have no clue from where this is importing the text cmsms_doctor.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the proper way of using React Hooks in Gutenberg on frontend? I'm mostly interested in useState. It works fine in edit.js, but in save.js it just breaks and it throws the minified React error, see below: I tried creating a separate .jsx component file but it throws the error when it encounters useState(). I tried importing it from both "react" and "@wordpress/element" packages. The component looks like this, something basic: Then I just imported it into save.js in my custom block: The Gutenberg plugin is installed, version 15.2.0.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom post type single page fine for admin, 404 from front When logged-in I can open post type single page (mysite.com/evenements/sample-slug)), but the same URL throws a 404 page if I'm not logged-in Sometimes when logged in, I edit a given single page then open it's URL, then open the same URL from another browser (not logged in) : it works fine ! The custom post type is created by a custom plugin, this is an extract from functions.php if ($theme === 'aep' && !function_exists('establishment_events')) { function establishment_events() { register_post_type('events', array( 'labels' => array( 'name' => 'Événements', 'singular_name' => 'Événement', 'add_new_item' => 'Ajouter un événement', 'edit_item' => 'Éditer un événement', 'view_item' => 'Voir un événement' ), 'public' => true, 'has_archive' => true, 'menu_position' => 5, 'rewrite' => array('slug' => 'evenements'), 'supports' => array('title', 'editor', 'revisions'), 'can_export' => true, 'menu_icon' => 'dashicons-calendar-alt', 'publicly_queryable' => true, )); // flush_rewrite_rules(); } add_action('init', 'establishment_events'); function post_listing_page() { global $post; if(!empty($post) && $post->post_type === 'events' ) { wp_enqueue_script( 'onpc-events-js', plugin_dir_url( __FILE__ ) . 'js/events.js' ); } } add_action( 'admin_enqueue_scripts', 'post_listing_page' ); } I didn't wrote the plugin, but I guess flush_rewrite_rules is not useful here so removed it. UPDATE It was very stupid but I found what's wrong : these posts are scheduled with 'post_status' => 'future'!! So it's normal that only admin can see the page ! But there is still something strange : everything works fine in localhost ! I can access future posts even if I'm not logged in ! This is why it as so hard to me to find what's wrong ! But I'd really like to know why I can't reproduce the same error in localhost !
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why the sites dropdown in multi-site installation is different from the list of sites when seen full page? I have a multi-site installation directory-based. When seen here https://freshideas.top/wp-admin/network/sites.php I see 4 sites: Instead in the dropdown, I see only 2 sites: In this other page https://freshideas.top/wp-admin/my-sites.php I see also only 2 sites: Question Why? A: Because they are not listing the same thing. * *one is a list of sites in the multisite, aka all 4 sites *the other is a list of sites that you have a role on, aka 2 sites To see all 4 sites you need a role on all sites. Being a super admin lets you browser the admin area of sites without needing a role, as the super admin flag overrides any checks.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Standard Regex syntax doesn't work in WordPress rewrite rule I've run into a regex issue while adding a rewrite rule into a Wordpress plugin. This blog has been helpful and the redirect works correctly after following this: https://brightminded.com/blog/mastering-wordpress-rewrite-rules/ However, I'm facing a challenge on this section: That's all fine, the redirect works perfectly. But I want to change the regex in the rewrite rule so that instead of matching city/{anything}/ it instead matches 'city/?{anything}`. And I'm running into an issue: The blog regex is invalid, yet it works The regex in the blog is ^city/([^/]*)/? and this works perfectly in the wordpress rewrite rule, however when I paste this into any online regex tool such as regex101.com or regexr.com, they say that the regex isn't valid: Valid regex expressions do not work I can easily create a regex that works correctly such as: ^city\/\?.* which matches to city/?{anything} just like I want. However, this regex doesn't work in the Wordpress rewrite rule. When I use this regex, and update permalinks in CMS, the redirect stops working. So far, I can't find any documentation for using regex in Wordpress so I would presume it follows the de facto standard. But please can anyone shed light on this? Does wordpress use a different standard for Regex and where is the documentation for this? Or is there a simple syntax error that I'm missing?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get parameters from the URL? I have to be missing something obvious, but darn me into wool socks if I can figure out what it is. I have a set of news articles in the custom post type news. I'm trying to get an archive page working where I can filter based on categories and tags. The bit I'm missing is how to get the information I need to build the query arguments. So, I have a URL somesite.com/category/announcements or somesite.com/tag/research-grants that goes to an archive page, in this case it pulls what it needs from archive-news.php in the theme. My question is how do I grab what category this is trying to access? I'm constructing my query like so: $args = array( 'post_type' => 'news' ); if ( /*Code that checks for category slug*/ ) { $args['category_name'] = /*Code that pulls category slug*/; } if ( /*Code that checks for tag slug*/ ) { $args['tag'] = /*Code that pulls tag slug*/; } // Execute query $news_query = new WP_Query($args); I've seen a lot about how to construct the query, but not much about how to actually pull the slug from the URL. Like I said, I have to missing something obvious here, but I can't figure it out.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Upgrading from Wordpress 3.8.2 to latest - only files and SQL dump available some friends of mine installed a WordPress instance at around 2013. Long story short: * *nothing was updated in all the time *a short while ago the admin pages weren't available anymore (just blank screen, error 500) *the former administrator doesn't care about the site anymore and just send me an SQL dump and the files from the webserver directory In the version.php file lists the versions wp 3.8.2, php 5.2.4, mysql 5.0 My goal is to get the site back up running with all of the content. The plan is to start the site locally, fix the admin pages, pull a backup through the admin panel and push it into a fresh install. My attempts: * *Installed latest wordpress in docker container, pushed the sql dump into the server -> WordPress error (wrong database format or something like this) *same as the first try, but with wordpress 3.9 (oldest image available) -> “Your PHP Installation Appears to Be Missing the MySQL Extension Which Is Required by WordPress” *mount the whole directory in the container of the previous attempt -> same error as above *to exclude a problem with docker i installed apache, php and mysql local on my machine -> same error My next step will be to install all I thought, that it should work if i install php and mysql with the specific versions mentioned in the version.php. Unfortunatly, i can't find them or i don't know how to install them. So. before i continue fooling around with my problem, i hope that someone did something similar and i don't have to "reinvent the wheel". I think my biggest problem is the missing knowledge about wordpress, php, mysql and maybe linux to solve this. Also i think (or hope) that there is a easier way to solve my problem. Thank's in advance A: If you can get an older version to work with the database (set up the config file to point to your local version of the DB), then you can try exporting it (via Export tool), and importing into another instance of the latest WP install (install a base site with a new DB). If only the content is important to you, you could extract just the posts table to get the post/page content via phpMyAdmin. Then import that into the new instance either manually or with some PHP programming (create a loop that goes through each of the post/page content of the old DB, then use WP functions to create a new post). You should be able to find guidance on the above processes with a bit of searching.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using the REST API filter, including two meta_queries breaks the response for one custom post type I'm using the WP REST API filter parameter plugin to be able to add filters to my REST requests. This works fine. Except, suddenly, adding two meta queries returns an Internal Server Error for, it seems, all post types. So, this is a problem: https://example.com/a/v4/wp-json/wp/v2/membership?_embed&_fields=_links,acf&page=1&filter[meta_query][0][key]=role&filter[meta_query][0][value]=admin&filter[meta_query][0][compare]=%27=%27&filter[meta_query][1][key]=group&filter[meta_query][1][value]=621227&filter[meta_query][1][compare]=%27=%27 These are not: https://example.com/a/v4/wp-json/wp/v2/membership?_embed&_fields=_links,acf&page=1&filter[meta_query][0][key]=role&filter[meta_query][0][value]=admin&filter[meta_query][0][compare]=%27=%27 https://example.com/a/v4/wp-json/wp/v2/membership?_embed&_fields=_links,acf&page=1&filter[meta_query][1][key]=group&filter[meta_query][1][value]=621227&filter[meta_query][1][compare]=%27=%27 Beyond a doubt, this worked up till very recently. I modify my API responses, but this problem persists after removing all my modifications. I have no idea where to start looking for what could be the underlying problem. Any ideas would be great. FWIW, removing the _embed and _fields parameters makes no difference. Update: I've been able to replicate this on another Wordpress install. A: Oddly, the cause of the problem seems to be the quotation marks around the comparison parameter. For example filter[meta_query][0][compare]=%27=%27 now needs to be filter[meta_query][0][compare]==. When only matching one meta value, this is not necessary, when matching two, this is, now, necessary. :/ Update: I realised that my hosting provider changed the version of Linux on my server around the same time. I can imagine this might be connected.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I have a website issue I am trying to resolve My website is jthomascrowne.com titled "The View From Here". I am currently using the Twenty Seventeen Theme on a Wordpress Business plan. I am relatively new to this. I know nothing about CSS. I tried and ditched Divi Builder. I have the following active plugins: Akismet-AntiSpam; Classic Editor; CoBlocks; Crowdsignal Forms and Polls and Ratings; Jetpack; Layout Grid; Page Optimizer; Wordpress.com Editing Toolkit; WP Rocket Load CSS; Yoast SEO. I have read a multitude of pages of instruction about categories, pages, designs, themes on WordPress as well as numerous other blogs/instructions/CSS modifications to get where I want to be. I renamed my site "The View From Here" from "Against the Wind" -- a political blog with a front page, a blog feed, and posts with subscriptions and an email list of about 100 created by me. The new title is so I can include more topics than politics. What I have been trying to do is have a front page with a little information and a place to subscribe (I did that part), then I want to go to my political posts on a page/category titled "Against the Wind". I want the page/category to have the same menu and the style of the front page but have different picture, title and a short intro followed by all my political posts. I want the same for my science posts/page/category, "Out of the Darkness". Ditto for "Mirror, Mirror", i.e., it's own picture, etc. I want to be able to expand this list/pages/categories/menu items as I write about other things -- each with it's own unique page. When I post, I want those on the email list to receive the post from the page/category it appears on/in,not from the front page. So far I have created a static front page with subscriptions allowed. I have created three additional pages and three additional categories as named above. I have populated them with pictures and text. I have created a menu that takes me to the other pages/categories (I have no idea whether they are pages or categories). When the menu takes me to "Against the Wind" it has its own picture under a squeezed picture of the title page (Can I eliminate the squeezed front page or make it smaller?). This is similar to other selected menu items. At one point, I got my political posts to appear when I selected "Against the Wind" from the menu, but there was no heading, no picture, no squeezed image of the front page, only my posts. Now the menu takes me to the page/category with the picture, but none of my posts are there... or anywhere visible on my site. Is there another theme that would work better for what I have in mind? Is it possible at all to get from where I am to where I want to be? If so, what do I need to do?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want to set the shipping_first_name metadata value to match the first_name metadata value for a User on registration using a function I'm using an Ultimate member registration form to enter user data, but I wanted to preset some fields so Users don't have to double key data. I'm finding the first_name metadata value is not populating the $userfirstname variable. If I hard code a value into the update_user_meta clause for the shipping_first_name, then it works, but when using the $userfirstname variable no value is assigned. The metakey is created against the correct user_id but the meta_value is empty. Any suggestions appreciated. Thanks Code below: add_action( 'user_register', function ( $user_id) { $user = get_user_by( 'ID', $user_id ); $userFirstName = ''; $userLastName = ''; $data = get_user_meta ( $user_id); $userFirstName = $data['first_name'][0]; $userLastName = $data['last_name'][0]; update_user_meta( $user_id, 'shipping_first_name', $userFirstName ); update_user_meta( $user_id, 'shipping_last_name', $userLastName ); });
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add custom styles to the Raft theme It seems that in WP6.1+ and the raft theme it's become much harder to customize styles. The footer has custom wp tags ala "wp-social-link" but in trying to override list-style-type in order so it doesn't have the default bullet the footer breaks (with valid json), style.css doesn't override anything even with a high specificity.. is there some trick to the raft theme I'm missing where I can customize styles? Original code in the footer: <!-- wp:social-link {"url":"https://domain.com/","service":"twitter"} /--> My attempts to specify a list style type of none <!-- wp:social-link {"style":{"list-style-type":"none"}}, "url":"https://domain.com/","service":"twitter"} /--> <!-- wp:social-link {"style":{"listStyleType":"none"}}, "url":"https://domain.com/","service":"twitter"} /--> The above two result in the social-link disappearing when switching from code to visual And in the Raft theme's style.css and end of assets/css/build/style.css (probably compiled but thought I'd try anyway) footer nav li.wp-social-link { list-style:none !important; } footer nav li.wp-social-link::marker { content: ""};
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get recent posts from wordpress RSS feed I tried to find a way to get the latest/recent posts that published on my website, but the Rss feed seems to be Sorted alphabetically, so its not show the recent posts and make the feed rss kind of useless. i find that it possible to change pages using /feed/?paged= but its not help me in my case i need to find a way to sort the feed rss by recent posts thanks A: Well i tried a lot until i tried feed/?orderby=latest it seem to work, hope it help other
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I improve and optimise my wordpress web server for better performance in 2023 How can I better optimise my Ubuntu 22.04.2 LTS wordpress website web server for better performance Well what I want to know is any good wordpress tricks that actually work well specially when it comes to cpu optimization because from there the problems start - current: php8.1-fpm, mariadb, nginx, fastcache cgi What else do you recommend ? .p.s. tips and tricks that actual work would help a lot thanks
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WordPress PHP8 Critical Error in class-wp-widget.php Recently updated to PHP8 and I'm getting a critical error related to the theme. The critical error is: Fatal error: Uncaught ArgumentCountError: Too few arguments to function WP_Widget::__construct(), 0 passed in /www/scottsimonbooks_396/public/wp-includes/class-wp-widget-factory.php on line 62 and at least 2 expected in /www/scottsimonbooks_396/public/wp-includes/class-wp-widget.php:163 Stack trace: #0 /www/scottsimonbooks_396/public/wp-includes/class-wp-widget-factory.php(62): WP_Widget->__construct() #1 /www/scottsimonbooks_396/public/wp-includes/widgets.php(115): WP_Widget_Factory->register('thinker_recentp...') #2 /www/scottsimonbooks_396/public/wp-content/themes/thinker/inc/widgets.php(78): register_widget('thinker_recentp...') #3 /www/scottsimonbooks_396/public/wp-content/themes/thinker/functions.php(241): require('/www/scottsimon...') #4 /www/scottsimonbooks_396/public/wp-settings.php(585): include('/www/scottsimon...') #5 /www/scottsimonbooks_396/public/wp-config.php(87): require_once('/www/scottsimon...') #6 /www/scottsimonbooks_396/public/wp-load.php(50): require_once('/www/scottsimon...') #7 /www/scottsimonbooks_396/public/wp-blog-header.php(13): require_once('/www/scottsimon...') #8 /www/scottsimonbooks_396/public/index.php(17): require('/www/scottsimon...') #9 {main} thrown in /www/scottsimonbooks_396/public/wp-includes/class-wp-widget.php on line 163 I tried updating class-wp-widget-factory.php on line 63 by swapping: $this->widgets[ $widget ] = new $widget(); for this $this->widgets[ $widget ] = new $widget( $widget, $widget ); but with no effect. ('thinker_recentp...') is a recent posts widget. The code at line 163 in wp-includes/class-wp-widget.php is: if ( ! empty( $id_base ) ) { $id_base = strtolower( $id_base ); } else { $id_base = preg_replace( '/(wp_)?widget_/', '', strtolower( get_class( $this ) ) ); } $this->id_base = $id_base; $this->name = $name; $this->option_name = 'widget_' . $this->id_base; $this->widget_options = wp_parse_args( $widget_options, array( 'classname' => str_replace( '\\', '_', $this->option_name ), 'customize_selective_refresh' => false, ) ); $this->control_options = wp_parse_args( $control_options, array( 'id_base' => $this->id_base ) ); }``` A: The error indicates that the WP_Widget::__construct() function expects at least two arguments to be passed but none were passed in the line of code where the error occurred. This could due to the upgrade to PHP 8 which is stricter about argument counts. To fix the issue, you need to modify the code in the "recent posts" widget class in ( wp-content/themes/thinker/inc/widgets.php) to include the required arguments in the constructor function for the WP_Widget class. You need to modify the line that creates a new instance of the WP_Widget class like this: Replace this code: parent::__construct( 'thinker_recentposts', __( 'Thinker Recent Posts', 'thinker' ), $widget_ops ); with this code: parent::__construct( 'thinker_recentposts', __( 'Thinker Recent Posts', 'thinker' ), array( 'description' => __( 'Displays recent posts with thumbnails', 'thinker' ) ) ); The difference is that we have added an array containing the "description" parameter, which is one of the required arguments for the WP_Widget constructor. Once you have made this change, save the file and try reloading. The error message should no longer appear..
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: wp cli media commands not working I am trying to bulk update media file captions through WP CLI so i can attribute image creators. My command is as follows: wp media list --date="2022-02-24" --format=ids | xargs -n 1 wp media meta update {} _wp_attachment_image_alt "&lt;a href='https://www.freepik.com/'&gt;Image by pch.vector on Freepik&lt;/a&gt;" I get these errors: Error: 'list' is not a registered subcommand of 'media'. See 'wp help media' for available subcommands. Error: 'meta' is not a registered subcommand of 'media'. See 'wp help media' for available subcommands I have the latest version, 2.7.1 On the WP CLI documentation, it lists media subcommands. There doesn't seem to be any subcommands for updating media meta. https://developer.wordpress.org/cli/commands/media/ Does this mean there isnt a capability of updating media meta through wp cli? A: Media is the post type (post_type="attachment"), so most operations are done with wp post command. By default, wp post manage blog posts (post_type="post"), therefore by fetching post IDs you must add --post_type=attachment indicating the type of posts. And to update media meta you should use wp post meta update <id> <key> <value> Your entire command could look like this: wp post list --date="2022-02-24" --format=ids --post_type=attachment | xargs -n 1 -I % wp post meta update % _wp_attachment_image_alt "{some meta value}"
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Edit multiple posts featured image Actually I imported posts from my another website, but I have only posts & their authors & their category & featured image is showing blank means not present. Now at every time I have to go to edit post then add featured image & then save. Is there any simple way to do this? (The old one is no more but I have Image files).
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Verify user login and password over api I run a unique website where users can purchase live streamed video content. We're in the very early stages of building an app for Android and iOS. I'm working on our own custom api separate of WordPress because we'll need some other functions in our API. I need to be able to verify a user on a mobile device (using an app) is authorized as a user. So I'll need to verify their login credentials over the API. It seems that WordPress has done some API updates recently, so I'm finding Google results to be all over the place. Can anyone point me in the right direction. My overall intent is to use the WordPress API to verify the login credentials of users, then pull their purchases from our website into our own API for reference when they're using the app. I just need to verify the user is able to login and is in fact our user, thus verifying username and password. Thanks Rob
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to properly move media files and update data? Bashing my head against a wall here. I want to write a function that moves the actual file of a Media Library attachment, but this must necessarily update all metadata. I am already doing a foreach on each attachment I want to move, calling the function... * *$post_attachment is an attachment object. *$existing_path is the item's existing path, minus the filename (basename) - eg: Users/robert/Sites/context.local/wp-content/uploads/media/folio/clients/ghost *$preferred_path is my intended destination for the file - eg. /Users/robert/Sites/context.local/wp-content/uploads/post/client/ghost The function should: * *Create the destination directory if it does not exist. *Move ALL sizes of images, not just the main/source one. *Include error handling. *Update all metadata. *Frankly, it also needs to update any <img src> references in post body content, too. I could either give the function the ID of a specific post object to which it is attached, or it should look for all references in the database, for safety. (This is not yet implemented below). The code below does successfully move the image file. But it does not update the metadata. In the admin, I am looking at a broken image and, after hard-refreshing the page to refresh cache, it's the same. I notice that the following, at the least, do not change after the function is run: * *the images' guid in the post table *the meta_values of meta_keys _wp_attached_file and _wp_attachment_metadata (weird serialised JSON array?) in the post_meta table What is the correct way to do this? function move_attachment_file($post_attachment, $existing_path, $preferred_path) { // Get the attachment ID $attachment_id = $post_attachment->ID; // Get the file paths of all sizes of the attachment $file_paths = array(); $metadata = wp_get_attachment_metadata($attachment_id); $file_paths[] = get_attached_file($attachment_id); foreach ($metadata['sizes'] as $size_info) { $file_paths[] = $existing_path . '/' . $size_info['file']; } // Define the new file paths $new_file_paths = array(); $new_file_paths[] = $preferred_path . '/' . basename($file_paths[0]); foreach (array_slice($file_paths, 1) as $size_file_path) { $new_file_paths[] = preg_replace( '#' . preg_quote($existing_path, '#') . '#', $preferred_path, $size_file_path ); } // Create the destination directory if it doesn't exist if (!file_exists(dirname($new_file_paths[0]))) { mkdir(dirname($new_file_paths[0]), 0755, true); } // Move the files $errors = array(); for ($i = 0; $i < count($file_paths); $i++) { if (!rename($file_paths[$i], $new_file_paths[$i])) { $errors[] = "Error moving file " . $file_paths[$i] . " to " . $new_file_paths[$i]; } } // Update attachment metadata foreach ($metadata['sizes'] as &$size_info) { $size_info['file'] = basename($new_file_paths[array_search($existing_path . '/' . $size_info['file'], $file_paths)]); } wp_update_attachment_metadata($attachment_id, $metadata); // Update image URLs in post content global $wpdb; $old_url = str_replace(site_url(), '', wp_get_attachment_url($attachment_id)); $new_url = str_replace(site_url(), '', wp_get_attachment_url($attachment_id, 'full')); $wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_content = REPLACE(post_content, %s, %s) WHERE post_content LIKE %s", $old_url, $new_url, "%" . $old_url . "%")); // Handle errors if (!empty($errors)) { return new WP_Error('file_move_error', implode("\n", $errors)); } else { return true; } }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamic name in href I would like to make the parameters "CONTENUTO_DINAMICO_ACF" dynamic by calling the Advanced Custom Fields in the post. How do I do this? <a href="#" class="bottone" onclick="reply_click(this)" nome="CONTENUTO_DINAMICO_ACF" cognome="CONTENUTO_DINAMICO_ACF">Titolo link</a> A: The get_field($field_name) function in ACF is what you'll need. Take a look at ACF's documentation about the function: ACF documentation. Basically, as long as you've created a field group for that page the <a> tag is on (by going to Custom Fields > Field Groups > (select your field group) > Settings > Location Rules), then you can use this function to dynamically populate anything. For example, if you have a custom field on that page named 'link_name', you can dynamically populate the field as so: <a href="#" nome="<?php echo get_field('link_name') ?>"></a>
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom Gallery Block - Uncaught TypeError: setAttributes is not a function I tried building my own custom gallery gutenberg block as shown here to get more familiar with the block structure. Putting all the code into a single file works fine, but when I try to split it up in edit.js and save.js, it returns this error upon trying to add images to it: "Uncaught TypeError: setAttributes is not a function" I wasn't able to resolve this, what's the issue? attributes in block.json "attributes": { "images" : { "type": "array" } }, edit.js /** * Retrieves the translation of text. * * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-i18n/ */ import { __ } from '@wordpress/i18n'; /** * React hook that is used to mark the block wrapper element. * It provides all the necessary props like the class name. * * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops */ import { useBlockProps, MediaUpload } from '@wordpress/block-editor'; import { Button } from '@wordpress/components'; //import {registerBlockType} from "@wordpress/blocks"; /** * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files. * Those files can contain any CSS code that gets applied to the editor. * * @see https://www.npmjs.com/package/@wordpress/scripts#using-css */ import './editor.scss'; /** * The edit function describes the structure of your block in the context of the * editor. This represents what the editor will render when the block is used. * * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit * * @return {WPElement} Element to render. */ export default function Edit(attributes, className, setAttributes) { const blockProps = useBlockProps(); // Getting the images of the array const {images = [] } = attributes; // to remove image from gallery const removeImage = (removeImage) => { //filter images const newImages = images.filter( (image) => { // if current image is equal to removeImage, image will be returend if(image.id != removeImage.id) { return image; } }); //save new state setAttributes({ images: newImages, }) } //Display the images const displayImages = (images) => { return ( //Loop through images images.map((image) => { return ( <div className="gallery-item-container"> <img className='gallery-item' src={image.url} key={ images.id } /> <div className='remove-item' onClick={() => removeImage(image)}><span class="dashicons dashicons-trash"></span></div> <div className='caption-text'>{image.caption[0]}</div> </div> ) }) ) } //JSX to return return ( <> <div {...blockProps}> <div className='gallery-grid'> {displayImages(images)} </div> <br/> <MediaUpload onSelect={(media) => setAttributes({ images: [...images,...media], }) } type="image" multiple={true} gallery={true} value={images} render={({open}) => ( <Button className="select-images-button is-button is-default is-large" onClick={open}> Add images </Button> )} /> </div> </> ); } A: Have you tried: export default function Edit( { attributes, className, setAttributes } ) { Edit is a react component, and react components receive props, so Edit( props ) is more accurate, hence the {} in the examples
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DNS entry for website on Server 1 below are website folder1 and folder2 structure where - posts/folder1 points to https://example.com/posts/folder1 posts/folder2 points to https://example.com/posts/folder2 So will the DNS entry be like below server 1 IP address -> https://example.com/posts/ On Server 2 has a wordpress in folder3 So posts/folder3 points to https://example.com/posts/folder3 So will the DNS entry be like below server 2 IP address -> https://example.com/posts/folder3 Does DNS resolve properly?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress custom endpoint returns Security violated Good day, im implement the a custom endpoint for my wordpress site, the intialization for my custom endpoint is: add_action( 'rest_api_init', function () { register_rest_route( '/v1', '/b2buser', array( 'methods' => 'POST', 'callback' => 'userMigration', 'permission_callback' => '__return_true' ) ); } ); When i call the endpoint sending body fields as JSON format, i capture the fields and im using wp_insert_user o wp_create_user but wordpress response me a message "Security violated" $userdata = array( 'user_login' => $request->get_param( 'USUARIO' ), 'user_pass' => $request->get_param( 'CLAVE' ), 'user_email' => $request->get_param( 'CORREO' ), 'first_name' => $request->get_param( 'NOMBRE_CONTACTO_PRINCIPAL' ), 'display_name' => $request->get_param( 'NOMBRE_CONTACTO_PRINCIPAL' ), 'role' => 'cliente_clase_b', 'locale' => 'es_ES', 'use_ssl'=> true, 'show_admin_bar_front' => 'true', "meta_input" => $meta ); $user_id = wp_insert_user( wp_slash($userdata )) ; if ( ! is_wp_error( $user_id ) ) { $res = new WP_REST_Response(['test'=>'11111']); $res->set_status(200); return ['req' => $user_id]; } return new WP_Error( 'error', __( $user_id->get_error_message(), "migration process" ) ); The error is weird, im using a basic auth. As additional note: when is use a GET and exclude the functions wp_create_user or wp_insert_user, wordpres response correctly, please i need a help with this issue, thank you.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What methods are you using to transfer individual WP site components from one site to another? We’ve built a moderately-large site consisting of about 500 pages, 60+ reusable blocks, a dozen page templates using GeneratePress Elements, etc. We need a way to transfer individual components of the site from development to production without disrupting the entire site and team by doing a full site copy. Doing a full site copy-and-replace isn’t a viable option; we have multiple developers working on multiple components at any given time in development, and we have multiple copywriters adding content at any given time in production. This kind of rules out full-site copy-and-replace in either direction. I tried using the WP export/import utility to transfer GP Elements. That works in a limited sense; it transfers the code (Gutenberg or no) from one system to another, and I have granular control over which Element is getting transferred. But it does not even attempt to carry over images the Element may be using as far as I can tell; I moved one and had to manually re-specify/connect the images, importing them into the media library first if they were not yet transferred. I’d also like to hear what people say about transferring Reusable Blocks, too. They suffer the same kinds of problems. One additional irritant is that, whether I transfer them using standard WP export/import, or use the more targeted Export as JSON method, when imported, updates to an element are imported as a new reusable block rather than replacing the existing one.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hooks to trigger a callback when adding, removing, rearranging or updating a widget in the widget area I am looking for hooks that fire when inside of Appearance -> Widgets: * *A widget gets added to a widget area *A widget gets deleted from a widget area *Widgets are being rearranged to new positions *A widget is being saved I am looking to trigger a callback function after any of these events occur. My callback function simply triggers the purge cache function of the caching plugins I am using. So far I have only found a hook called delete_widget, which gets triggered when a widget is being deleted. add_action( "delete_widget", "my_function_purge_cache" , 10, 3); This works as intended. However I can't find hooks for the other 3 events. Reading through class-wp-widget.php I can see widgets use update_option to save any changes made to the widgets, including adding, removing, reordering and saving a widget. update_option does have a hook called updated_option which fires after a setting has been successfully updated. I tested this hook using: add_action( 'updated_option', 'my_function_purge_cache', 10, 3 ); and it seems to work as expected. My function is being called on all 4 events that I was looking for. However this might be an overkill as this gets triggered whenever any option is updated across WordPress and I have no idea how often this occurs. Worst case some 3rd party plugin calls update_option during each page visit. A: I ended up using the updated_option hook and checking if a widget or sidebar has been updated. When a widget is added, removed or saved, the update_option hook is fired. All widget option names start with "widget_". By checking if the option name starts with "widget_" we can determine if a widget was added, removed or saved. When widgets are being reordered within a widget area, the new positions are being saved to the option sidebars_widgets. The hook updated_option fires immediately after an option has been successfully updated. Note: updated_option will not fire if the old value and the new value are the same. function purge_cache_on_widget_change( $option, $old_value, $value ) { if( substr( $option, 0, 7 ) === 'widget_' || $option === 'sidebars_widgets' ) { my_function_purge_cache(); } } add_action('updated_option','purge_cache_on_widget_change', 10, 3);
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling get_header() with installed FSE theme I'm working on a plugin that adds a custom WP rewrite rule using add_rewrite_rule() and I'm loading a custom template for that rule using template_include hook and passing the template path to that hook, so when the user visits that URL, the template is rendered successfully. The template itself contains get_header() on the top and get_footer() at the bottom, and they are working as expected. The problem comes when I install Full Site Editing themes like 'twenty twenty three', and I see this errors: Deprecated: File Theme without header.php is deprecated since version 3.0.0 with no alternative available. Please include a header.php template in your theme. in /path/to/wp_installation/wp-includes/functions.php on line 5583 Deprecated: File Theme without footer.php is deprecated since version 3.0.0 with no alternative available. Please include a footer.php template in your theme. in /path/to/wp_installation/wp-includes/functions.php on line 5583 I know that the FSE themes are blocks, so how can I load the header block and the footer block? Also, I want to know how to check if the active theme is FSE theme or not. Update 1 I tried to create a custom page template and used get_header() and get_footer() functions inside that template, and it raises the same errors. Update 2 I found that this is related to this ticket on WordPress core trac.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you manually define the post id va WP All Import plugin? Search the documentation for WPAllImport but not finding how to define the post ID when importing a file. Is this even possible considering the way posts IDs are sequential? For example, this is the url to edit the post (woocommerce product) /wp-admin/post.php?post=787&action=edit If you have no posts/items, is there a way to define the post ID # within your import? And can I use say a SKU number as the post ID #? Help me Obi Wan you are my only hope
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what to do after instlling cyberpanel on VPS I am upgrading from shared hosting to VPS hosting, so I went with digitalocean and used marketplace to create a droplet with cyberpanel, linked my domain to the droplet, moved data, and almost done. but my question is what to do after this? are there any security steps should I take ? or something that should I care about except cyberpanel dashboard and my website ?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WordPress / PHP: Check if column has value and then check if value in array I have a table called wp_invites which contains a list of names (and other data) for those invited to an event. Below are 4 rows from the table: id handler lead_name party reference invited_to_reception reception_list 1 Freddy John John, Ben, Steven NgxaIyNybK4O yes 2 Jason Peter Peter, Jamie, Cathy 6iqIWqdxewf0 yes Peter, Cathy 3 Jason Mark Mark Mx7z9UnCPOQo yes 4 Jason Kate Kate, Louise, Lucy gumWlKmfmyXg no To explain the above: * *Only certain groups are invited to the reception (defined by invited_to_reception) *In some instances, only certain members of a party are invited to the reception. If invited_to_reception is yes and that row has no reception_list defined, then everyone in the party is invited. If reception_list has values, then only those members from party are invited. *reference is unique identifier which determines which invite to show. For example, rsvp.com?ref=NgxaIyNybK4O will show invites for "John, Ben, Steven" What I'm trying to do is check if the names in reception_list are in party and if so, show them a checkbox option to ask if they're attending the reception. Current methodology: <?php // get reference from URL to determine which invites to show $reference = ( isset( $_GET['ref'] ) ) ? sanitize_text_field( $_GET['ref'] ) : ''; // check if valid invite (if ref exists in wp_invites table) $invites_table = $wpdb->prefix . 'invites'; $results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $invites_table WHERE reference=%s", $reference), ARRAY_A ); if($results): foreach ($results as $result): $party = $result['party']; $party_guests = explode(",", $party); $invited_to_reception = $result['invited_to_reception']; $reception_list = $result['reception_list']; $reception_list = explode(",", $reception_list); // $reception_list = (array) $reception_list; // convert to assoc array foreach ($party_guests as $index=>$guest): $guest_name = trim($guest); if ($invited_to_reception == "Yes"): if( in_array($guest_name, $reception_list) ): ?> Show checkbox options for reception <?php endif; endif; endforeach endforeach; endif; ?> Issues with the above: * *Firstly, for the row with id 1, invited_to_reception is "yes" meaning everyone in party is invited. However, when I access that invite, it does not show the reception checkbox. Naturally this is because I have an in_array() check running beforehand, but unsure how I can run both instances (where all are invited and in other cases some are invited) without duplicating the code? *For the row with id 2, only 2 people from party are invited to the reception. However, when I access this invite, only one of the names has the reception checkboxes, when it should appear for both of them.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove category and other tags from posts page On my website I have a primary menu. Under this menu, I have links for categories. When a user clicks these menu links, they're redirected to a landing page with all posts that are marked for that category. Currently the landing page for the category displays the category selected, as well as what appear to be tags(?), at the top of the recent post listing for that category. Please see the yellow box in the screenshot below: How can I remove these auto generated fields from the page (in the yellow box)? I just want the landing page for the category to display my most recent posts, and to not display the category type or the tags(?) associated with the posts there. Thanks in advance for any help you can provide.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress Woocommerce Store/Products won't load properly On the store page of my website, the products wont load properly. The store page should be 5 products wide and when you click on a product listing, the page is very basic and at the bottom it says "There has been a critical error on this website" Any ideas? TIA! https://theroadlesswritten.com.au/store/ https://theroadlesswritten.com.au/product/big-brook-dam-print/
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Site very slow after changing wordpress theme and CPU at 99% Here is the website. Loads very fast once its cached but if a page is not cache it takes forever to load why ? worked very fine before I changed to a new theme
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't edit the widgets sidebar or footer Why can't I edit my widgets sidebar ? website can be found here.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use filter in this situation, can not modify the structure using filter plugins/idx-broker-platinum/idx/shortcodes/register-impress-shortcodes.php This is the plugin file where I need to use a filter to override the structure. Filter name: impress_showcase_property_html class Register_Impress_Shortcodes <?php /** * Property_showcase_shortcode function. * * @access public * @param array $atts (default: array()) * @return void */ public function property_showcase_shortcode( $atts = array() ) { extract( shortcode_atts( array( 'max' => 4, 'use_rows' => 1, 'num_per_row' => 4, 'show_image' => 1, 'order' => 'default', 'property_type' => 'featured', 'saved_link_id' => '', 'agent_id' => '', 'styles' => 1, 'new_window' => 0, 'colistings' => 1, ), $atts ) ); if ( ! empty( $styles ) ) { wp_enqueue_style( 'impress-showcase' ); } $output = ''; if ( ( $property_type ) === 'savedlinks' ) { $properties = $this->idx_api->saved_link_properties( $saved_link_id ); $output .= '<!-- Saved Link ID: ' . $saved_link_id . ' -->'; } else { $properties = $this->idx_api->client_properties( $property_type ); $output .= '<!-- Property Type: ' . $property_type . ' -->'; } // Force type as Array. $properties = json_encode( $properties ); $properties = json_decode( $properties, true ); // If no properties or an error, load message if ( empty( $properties ) || ( isset( $properties[0] ) && $properties[0] === 'No results returned' ) || isset( $properties['errors']['idx_api_error'] ) ) { if ( isset( $properties['errors']['idx_api_error'] ) ) { return $output .= '<p>' . $properties['errors']['idx_api_error'][0] . '</p>'; } else { return $output .= '<p>No properties found</p>'; } } $total = count( $properties ); $count = 0; $column_class = ''; if ( 1 == $use_rows ) { // Max of four columns $number_columns = ( $num_per_row > 4 ) ? 4 : (int) $num_per_row; // column class switch ( $number_columns ) { case 0: $column_class = 'columns small-12 large-12'; break; case 1: $column_class = 'columns small-12 large-12'; break; case 2: $column_class = 'columns small-12 medium-6 large-6'; break; case 3: $column_class = 'columns small-12 medium-4 large-4'; break; case 4: $column_class = 'columns small-12 medium-3 large-3'; break; } } if ( ! isset( $new_window ) ) { $new_window = 0; } $target = $this->target( $new_window ); if ( 'low-high' == $order ) { // sort low to high usort( $properties, array( $this->idx_api, 'price_cmp' ) ); } if ( 'high-low' == $order ) { usort( $properties, array( $this->idx_api, 'price_cmp' ) ); $properties = array_reverse( $properties ); } // Used to hold agent data when matching for colistings. $agent_data; foreach ( $properties as $prop ) { if ( ! empty( $agent_id ) ) { // Check if listing agent ID matches agent's IDX ID. if ( empty( $prop['userAgentID'] ) || (int) $agent_id !== (int) $prop['userAgentID'] ) { // If colistings is enabled, check for match. if ( $colistings ) { if ( array_key_exists( 'coListingAgentID', $prop ) ) { // Check if $agent_data is already set, if not grab a new copy to get MLS-provided agent ID. if ( empty( $agent_data ) ) { $agent_data = $this->idx_api->idx_api( 'agents?filterField=agentID&filterValue=' . $agent_id, IDX_API_DEFAULT_VERSION, 'clients', [], 7200, 'GET', true ); } // Check the listing's coListingAgentID against the agent's raw MLS-provided ID, continues if no match. if ( empty( $agent_data['agent'][0]['listingAgentID'] ) || $agent_data['agent'][0]['listingAgentID'] !== $prop['coListingAgentID'] ) { continue; } } else { // Listing does not have coListingAgentID field data to match against. continue; } } else { // Colistings setting is not enabled. continue; } } } if ( ! empty( $max ) && $count == $max ) { return $output; } $prop_image_url = $prop['image']['0']['url'] ?? $prop['image']['1']['url'] ?? plugins_url( '/idx-broker-platinum/assets/images/noPhotoFull.png' ); if ( 1 == $use_rows && $count == 0 && $max != '1' ) { $output .= '<div class="shortcode impress-property-showcase impress-row">'; } if ( empty( $prop['propStatus'] ) ) { $prop['propStatus'] = 'none'; } $count++; // Add Disclaimer when applicable. if ( isset( $prop['disclaimer'] ) && ! empty( $prop['disclaimer'] ) ) { foreach ( $prop['disclaimer'] as $disclaimer ) { if ( in_array( 'widget', $disclaimer ) ) { $disclaimer_text = $disclaimer['text']; $disclaimer_logo = $disclaimer['logoURL']; } } } // Add Courtesy when applicable. if ( isset( $prop['courtesy'] ) && ! empty( $prop['courtesy'] ) ) { foreach ( $prop['courtesy'] as $courtesy ) { if ( in_array( 'widget', $courtesy ) ) { $courtesy_text = $courtesy['text']; } } } $prop = $this->set_missing_core_fields( $prop ); // Get URL and add suffix if one exists if ( isset( $prop['fullDetailsURL'] ) ) { $url = $prop['fullDetailsURL']; } else { $url = $this->idx_api->details_url() . '/' . $prop['detailsURL']; } if ( has_filter( 'impress_showcase_property_url_suffix' ) ) { $url = $url . apply_filters( 'impress_showcase_property_url_suffix', $suffix = http_build_query( array() ), $prop, $this->idx_api ); } if ( 1 == $show_image ) { $output .= apply_filters( 'impress_showcase_property_html', sprintf( '<div class="impress-showcase-property %17$s"> <a href="%3$s" class="impress-showcase-photo" target="%18$s"> <img src="%4$s" alt="%5$s" title="%6$s %7$s %8$s %9$s %10$s, %11$s" /> <span class="impress-price">%1$s</span> <span class="impress-status">%2$s</span> <p class="impress-address"> <span class="impress-street">%6$s %7$s %8$s %9$s</span> <span class="impress-cityname">%10$s</span>, <span class="impress-state"> %11$s</span> </p> </a> <p class="impress-beds-baths-sqft"> %12$s %13$s %14$s %15$s </p> %16$s </div>', price_selector( $prop ), $prop['propStatus'], $url, $prop_image_url, htmlspecialchars( $prop['remarksConcat'] ), $prop['streetNumber'], $prop['streetDirection'], $prop['streetName'], $prop['unitNumber'], $prop['cityName'], $prop['state'], $this->hide_empty_fields( 'beds', 'Beds', ( empty( $prop['bedrooms'] ) ? '' : $prop['bedrooms'] ) ), $this->hide_empty_fields( 'baths', 'Baths', ( empty( $prop['totalBaths'] ) ? '' : $prop['totalBaths'] ) ), $this->hide_empty_fields( 'sqft', 'SqFt', ( empty( $prop['sqFt'] ) ? '' : $prop['sqFt'] ) ), $this->hide_empty_fields( 'acres', 'Acres', ( empty( $prop['acres'] ) ? '' : $prop['acres'] ) ), $this->maybe_add_disclaimer_and_courtesy( $prop ), $column_class, $target ), $prop, ( isset( $instance ) ? $instance : [] ), $url, $prop_image_url, $this->maybe_add_disclaimer_and_courtesy( $prop ), $column_class, $target ); } else { $output .= apply_filters( 'impress_showcase_property_list_html', sprintf( '<li class="impress-showcase-property-list %13$s"> <a href="%2$s" target="%14$s"> <p> <span class="impress-price">%1$s</span> <span class="impress-address"> <span class="impress-street">%3$s %4$s %5$s %6$s</span> <span class="impress-cityname">%7$s</span>, <span class="impress-state"> %8$s</span> </span> <span class="impress-beds-baths-sqft"> %9$s %10$s %11$s %12$s </span> </p> </a> </li>', price_selector( $prop ), $url, $prop['streetNumber'], $prop['streetDirection'], $prop['streetName'], $prop['unitNumber'], $prop['cityName'], $prop['state'], $this->hide_empty_fields( 'beds', 'Beds', ( empty( $prop['bedrooms'] ) ? '' : $prop['bedrooms'] ) ), $this->hide_empty_fields( 'baths', 'Baths', ( empty( $prop['totalBaths'] ) ? '' : $prop['totalBaths'] ) ), $this->hide_empty_fields( 'sqft', 'SqFt', ( empty( $prop['sqFt'] ) ? '' : $prop['sqFt'] ) ), $this->hide_empty_fields( 'acres', 'Acres', ( empty( $prop['acres'] ) ? '' : $prop['acres'] ) ), $column_class, $target ), $prop, ( isset( $instance ) ? $instance : [] ), $url, $column_class, $target ); } if ( 1 == $use_rows && ( 1 !== $count || 1 === $total ) ) { // close a row if.. // num_per_row is a factor of count OR // count is equal to the max number of listings to show OR // count is equal to the total number of listings available if ( $count % $num_per_row == 0 || $count == $total || $count == $max ) { $output .= '</div> <!-- .impress-row -->'; } // open a new row if.. // num per row is a factor of count AND // count is not equal to max AND // count is not equal to total if ( $count % $num_per_row == 0 && $count != $max && $count != $total ) { $output .= '<div class="impress-row shortcode impress-property-showcase">'; } } } return $output; } I can not understand how to override $this in functions PHP. what is the proper way to do that? Added filter code to my functions.php add_filter('impress_showcase_property_html', 'impress_showcase_property_html_callback', 10, 8); if(!function_exists('impress_showcase_property_html_callback')) { /** * Update Layout * @param $prop * @param $url * @param $prop_image_url * @param $column_class * @param $target * * @return string */ function impress_showcase_property_html_callback($value, $prop, $instance, $url, $prop_image_url, $column_class, $target){ $value = sprintf( '<div class="impress-showcase-property %17$s"> <a href="%3$s" class="impress-showcase-photo" target="%18$s"> <img src="%4$s" alt="%5$s" title="%6$s %7$s %8$s %9$s %10$s, %11$s" /> <span class="impress-price">%1$s</span> <span class="impress-status">%2$s</span> </a> <p class="impress-address"> <span class="impress-street">%6$s %7$s %8$s %9$s</span> <span class="impress-cityname">%10$s</span>, <span class="impress-state"> %11$s</span> </p> <p class="impress-beds-baths-sqft"> %12$s %13$s %14$s %15$s </p> %16$s </div>', price_selector( $prop ), $prop['propStatus'], $url, $prop_image_url, htmlspecialchars( $prop['remarksConcat'] ), $prop['streetNumber'], $prop['streetDirection'], $prop['streetName'], $prop['unitNumber'], $prop['cityName'], $prop['state'], $this->hide_empty_fields( 'beds', 'Beds', ( empty( $prop['bedrooms'] ) ? '' : '<span class="numbers">'.$prop['bedrooms'].'</span>' ) ), $this->hide_empty_fields( 'baths', 'Baths', ( empty( $prop['totalBaths'] ) ? '' : '<span class="numbers">'.$prop['totalBaths'].'</span>' ) ), $this->hide_empty_fields( 'sqft', 'SqFt', ( empty( $prop['sqFt'] ) ? '' : '<span class="numbers">'.$prop['sqFt'].'</span>' ) ), $this->hide_empty_fields( 'acres', 'Acres', ( empty( $prop['acres'] ) ? '' : '<span class="numbers">'.$prop['acres'].'</span>' ) ), $this->maybe_add_disclaimer_and_courtesy( $prop ), $column_class, $target ); return $value; } } A: So you're trying to call the hide_empty_fields() and maybe_add_disclaimer_and_courtesy() methods in the Register_Impress_Shortcodes class, from within a global function, and it's not impossible to call class methods from within such global functions, but you cannot use $this in your function because $this is only available from within a class method which is called from within an object context. More details in the PHP manual As for the proper way to call those two class methods from within your function, I'm not sure (unless maybe, if you provide the full class code and the information on how/when/where it's being instantiated), but see below for some options that you can try, without modifying the core plugin files: * *If those methods are public and there's an instance of the class in the global scope, e.g. global $Register_Impress_Shortcodes; $Register_Impress_Shortcodes = new Register_Impress_Shortcodes();, then just add global $Register_Impress_Shortcodes; to your function (at the top), then replace those $this with $Register_Impress_Shortcodes. *If such global instance is not available, but those methods are public and there is a "static instance getter" like the DBConn::getConn() here, then in your function, just replace the $this with Register_Impress_Shortcodes::instance() (or replace instance with the correct method name). If such method doesn't exist, but/or the plugin in question provides a global function like register_impress_shortcodes_instance(), which returns the class instance, then replace those $this with register_impress_shortcodes_instance(). *If those methods are not public or there's no global class instance, and neither an instance getter method or function, and that the Register_Impress_Shortcodes class can be extended, and also that those methods are not private, then you can do something like this: <?php // Extend the class. class My_Register_Impress_Shortcodes extends Register_Impress_Shortcodes { public function __construct() { // Add your filter. add_filter( 'impress_showcase_property_html', array( $this, 'impress_showcase_property_html_callback' ), 10, 7 ); } // Now this is your filter callback which is a method in this class. So // you can now use $this and access the methods hide_empty_fields() and // maybe_add_disclaimer_and_courtesy() defined in the parent class. public function impress_showcase_property_html_callback( $value, $prop, $instance, $url, $prop_image_url, $column_class, $target ) { $value = sprintf( '... your code here', price_selector( $prop ), $prop['propStatus'], $url, $prop_image_url, htmlspecialchars( $prop['remarksConcat'] ), $prop['streetNumber'], $prop['streetDirection'], $prop['streetName'], $prop['unitNumber'], $prop['cityName'], $prop['state'], parent::hide_empty_fields( 'beds', 'Beds', ( empty( $prop['bedrooms'] ) ? '' : '<span class="numbers">'.$prop['bedrooms'].'</span>' ) ), parent::hide_empty_fields( 'baths', 'Baths', ( empty( $prop['totalBaths'] ) ? '' : '<span class="numbers">'.$prop['totalBaths'].'</span>' ) ), parent::hide_empty_fields( 'sqft', 'SqFt', ( empty( $prop['sqFt'] ) ? '' : '<span class="numbers">'.$prop['sqFt'].'</span>' ) ), parent::hide_empty_fields( 'acres', 'Acres', ( empty( $prop['acres'] ) ? '' : '<span class="numbers">'.$prop['acres'].'</span>' ) ), parent::maybe_add_disclaimer_and_courtesy( $prop ), $column_class, $target ); return $value; } } function init_my_register_impress_shortcodes() { new My_Register_Impress_Shortcodes(); } add_action( 'init', 'init_my_register_impress_shortcodes' ); Note: Be sure to remove the add_filter('impress_showcase_property_html', 'impress_showcase_property_html_callback', 10, 8); in your code. *If the class cannot be extended or you're having trouble calling those methods from within your class, then I guess you would want to unregister/remove the shortcode added by that class/plugin, then copy that very class, rename it and re-add the shortcode you have removed. That way, you wouldn't need to hook on impress_showcase_property_html and simply modify the shortcode output in the property_showcase_shortcode() method... But the problem with this (and the previous option), is that when the plugin is updated, you would need to revise your class/methods so that it's in sync with the latest code in the updated plugin. Another option that you can try, is if possible, create 2 global functions (e.g. my_hide_empty_fields() and my_maybe_add_disclaimer_and_courtesy()) which does what those methods do, respectively, i.e. basically copy the code in those methods... and edit it accordingly, e.g. remove any $this calls. Then just use your functions from within your impress_showcase_property_html_callback() function.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change post-name when inserting new Post if Specific Category is selected in WP I want to hook a function for first time when new post is being inserted in WP. when Poetry category is selected I want to change post-name with random 7 numeric numbers like /poetry/2837410/ which function should I call that triger only once when new post is posting A: You can use the wp_insert_post_data filter, and check the post_category array for your category ID. (If $update is false, you'll know it's a new post being added, not an existing post being edited.) Something like this should work. add_filter( 'wp_insert_post_data', 'wpse414180_maybe_change_slug', 10, 4 ); /** * Changes the slug on posts in the Poetry category. * * @param array $data The sanitized, slashed, processed post data. * @param array $postarr The sanitized, slashed post data. * @param array $unclean The slashed post data. Unsanitized. We won't use this. * @param bool $update Is this a post update? * @return array The (possibly filtered) post data. */ function wpse414180_maybe_change_slug( $data, $postarr, $unclean, $update ) { if ( $update ) { // This is an existing post being updated; return. return $data; } $poetry_category = get_category_by_slug( 'poetry' ); if ( empty( $poetry_category ) ) { // No poetry category, so we return early. return $data; } if ( in_array( $poetry_category->term_id, $postarr['post_category'] ) ) { // Random 7-digit number. Note: no collision checking. $data['post_name'] = rand( 1000000, 9999999); } return $data; } Note This code is untested and meant as a starting point, not necessarily a finished product; try it out on a test site first. I haven't added anything to make sure a given slug (ie, post_name) isn't already in use. References * *wp_insert_post_data *get_category_by_slug() *in_array() *rand()
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the standard way to use the version of React that ships with Gutenberg on the front end? I want to create a Gutenberg block that uses React on the client rendered page (not the admin pages). * *Is React code split from the rest of Gutenberg? *If so, how can I enqueue that specific bundled React to be used? A: I found it, wp-element. The @wordpress/scripts should handle the heavy lifting of transforming the JSX in the proper way. add_action( 'wp_enqueue_scripts', 'my_enqueue_plugin_js' ); // Loads on frontend function my_enqueue_plugin_js() { wp_enqueue_script( 'my-plugin-frontend', plugin_dir_url( __FILE__ ) . 'js/plugin.js', ['wp-element'] ); } Once we do this we will have window.wp.element available in our JavaScript. This contains the ReactDOM render() function as well as createElement() if you wanted to write React without JSX. -- How to Enqueue React in A WordPress Theme or Plugin
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Browser Caching .htaccess I must be missing something. Here is the excerpt from my 'htaccess file'; <IfModule mod_expires.c> ExpiresActive On # Images ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/webp "access plus 1 year" ExpiresByType image/svg+xml "access plus 1 year" ExpiresByType image/x-icon "access plus 1 year" # Video ExpiresByType video/webm "access plus 1 year" ExpiresByType video/mp4 "access plus 1 year" ExpiresByType video/mpeg "access plus 1 year" # Fonts ExpiresByType font/ttf "access plus 1 year" ExpiresByType font/otf "access plus 1 year" ExpiresByType font/woff "access plus 1 year" ExpiresByType font/woff2 "access plus 1 year" ExpiresByType application/font-woff "access plus 1 year" # CSS, JavaScript ExpiresByType text/css "access plus 1 year" ExpiresByType text/javascript "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" # Others ExpiresByType application/pdf "access plus 1 year" ExpiresByType image/vnd.microsoft.icon "access plus 1 year" </IfModule> I've used this on various sites with no issues previously, but today I am noticing only a few files are being cached. What have I done wrong?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Place the Featured image on a post, before the first via code I'm making a custom theme andar I need to place the featured image, right before the first of a post, via code. I don't know if it's even possible. The idea is, somehow, in the loop, get the first Sutbtitle and place the featured image. Any ideas? Thanks in advance!!! THIS IS POST TITLE This is the first paragraph consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. THIS IS THE FIRST SUBTITLE OF THE POST The featured image is rendered before the first subtitle - Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extend search query to search meta keys values based on search string I want to create an autocomplete AJAX search and I'm trying to have it where when the user starts typing, the list populates titles matching that search string. My issue is in the WP_query, because I want to search the title, content and search meta key values and show the results. I will be searching the rfi_antenna_sku meta key and alive_antenna_sku meta key, etc for the product post type. My Query: // the ajax function add_action('wp_ajax_data_fetch' , 'data_fetch'); add_action('wp_ajax_nopriv_data_fetch','data_fetch'); function data_fetch(){ $args = array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => array('product'), 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'rfi_antenna_sku', 'value' => esc_attr( $_POST['keyword'] ), 'compare' => 'LIKE', ), array( 'key' => 'alive_antenna_sku', 'value' => esc_attr( $_POST['keyword'] ), 'compare' => 'LIKE', ) ) ); $the_query = new WP_Query( $args ); if( $the_query->have_posts() ) : echo '<ul>'; while( $the_query->have_posts() ): $the_query->the_post(); ?> <li><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></li> <?php endwhile; echo '</ul>'; wp_reset_postdata(); endif; die(); } In case it helps future people, here's the rest: function antennas_competitive_search_form() { $output = '<div class="search_bar">'; $output .= '<form action="/" method="get" autocomplete="off">'; $output .= '<input type="text" name="s" placeholder="Search Code..." id="keyword" class="input_search" onkeyup="fetch()">'; $output .= '<button>'; $output .= 'Search'; $output .= '</button>'; $output .= '</form>'; $output .= '<div class="search_result" id="datafetch">'; $output .= '<ul>'; $output .= '<li>Please wait..</li>'; $output .= '</ul>'; $output .= '</div>'; $output .= '</div>'; return $output; } /** * Ajax Search */ // add the ajax fetch js add_action( 'wp_footer', 'ajax_fetch' ); function ajax_fetch() { ?> <script type="text/javascript"> function fetch(){ jQuery.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', type: 'post', data: { action: 'data_fetch', keyword: jQuery('#keyword').val() }, success: function(data) { jQuery('#datafetch').html( data ); } }); } </script> <?php } And lastly, the links I've researched before posting here: WP_Query with meta_value LIKE 'something%' Get posts by meta value How to search for meta_query LIKE or tax_query LIKE and grab these posts on search results? Using meta query ('meta_query') with a search query ('s')
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to update Wordpress plugins from external website with nodejs? I'm building a website in nodejs. what I want to achieve is the following: * *Connect to different wordpress websites using the API REST (this step is done) *List all the plugins available in those website (this step is done) - in the example I only put one. *I want to know if there is any update available for the plugins, and update from my custom nodejs site. This is my code for listings the plugins, I can retrieve the custom version, but I can't find the latest version. const siteUrl = "https://example.com/"; const plugins_endpoint = "wp-json/wp/v2/plugins/"; const pluginsUrl = siteUrl + plugins_endpoint; const token = Buffer.from(`${username}:${password}`).toString("base64"); const config = { headers: { "Content-Type": "application/json", Authorization: `Basic ${token}`, }, }; async function getPluginList() { const response = await axios.get(pluginsUrl, config); return response.data; } getPluginList() .then((data) => { data.forEach((element) => { console.log("Plugin name: ", element.name); console.log("status: ", element.status); console.log("current Version: ", element.version); console.log("Textdomain: ", element.textdomain); console.log("Links: ", element._links); }); }) .catch((error) => { console.error(error); }); A: Assuming a private plugin, not available via the repository, there are several search results for 'wordpress private update' that might be helpful. In fact, I recall doing it once several (many) years ago, but can't find how I did it. (And I seem to recall posting the answer here on SO, but can't find that either.) But, one of the search results is here https://rudrastyh.com/wordpress/self-hosted-plugin-update.html . The process is a bit complex. I have a few private plugins that I have written that I use on the sites I manage. But since I wrote them, I know when they change, and I manually update on the sites I manage. They aren't anywhere else, so don't have to worry about any automatic processes. Added If you are looking for a plugin that will update other sites, there are a few that already do that. But they require their plugin on the additional sites, to provide an 'authentication' to the admin area of that other site. One I use is "Infinite WP", which is a manager for multiple sites. Each site has their plugin installed, and then the 'master' site accesses those sites (via the plugin) to perform updates and other functions. Works quite well. If you are looking for a way to 'enumerate' plugins on another sites that you do not own or manage, then that sounds a bit 'black-hacky', and I can't help you there.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .po file is loaded but changes are not appearing I made a translation file (fr_CA) and it's loading. But any change I make in the file does not appear on website. Clear cache, private window, other browser. It's all the same. I don't get it... What am I doing wrong?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can i link threejs in my functions.php file in understrap theme i'm trying to create a portfolio website with wordpress understrap and i want to integrate threejs in the website, only it's not showing on the page and i dont know how to link the threejs code in functions.php file // Exit if accessed directly. defined( 'ABSPATH' ) || exit; // UnderStrap's includes directory. $understrap_inc_dir = 'inc'; // Array of files to include. $understrap_includes = array( '/theme-settings.php', // Initialize theme default settings. '/setup.php', // Theme setup and custom theme supports. '/widgets.php', // Register widget area. '/enqueue.php', // Enqueue scripts and styles. '/template-tags.php', // Custom template tags for this theme. '/pagination.php', // Custom pagination for this theme. '/hooks.php', // Custom hooks. '/extras.php', // Custom functions that act independently of the theme templates. '/customizer.php', // Customizer additions. '/custom-comments.php', // Custom Comments file. '/class-wp-bootstrap-navwalker.php', // Load custom WordPress nav walker. Trying to get deeper navigation? Check out: https://github.com/understrap/understrap/issues/567. '/editor.php', // Load Editor functions. '/block-editor.php', // Load Block Editor functions. '/deprecated.php', // Load deprecated functions. ); // Load WooCommerce functions if WooCommerce is activated. if ( class_exists( 'WooCommerce' ) ) { $understrap_includes[] = '/woocommerce.php'; } // Load Jetpack compatibility file if Jetpack is activiated. if ( class_exists( 'Jetpack' ) ) { $understrap_includes[] = '/jetpack.php'; } // Include files. foreach ( $understrap_includes as $file ) { require_once get_theme_file_path( $understrap_inc_dir . $file ); } how can i link my threejs file in here? thank you for helping.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Last Logged In Sortable Column I've added the code found here and slightly modified it so that the "Last Logged In" column is sortable but it doesn't sort the column correctly when I click it, can anyone see anything wrong with the code? Thanks // add two columns to the user list page add_filter( 'manage_users_columns', 'my_manage_users_columns' ); function my_manage_users_columns( $columns ) { $columns['registration_date'] = 'Registered'; $columns['last_login_date'] = 'Last Logged In'; return $columns; } // provide data for the two added columns add_filter( 'manage_users_custom_column', 'my_manage_users_custom_column', 10, 3 ); function my_manage_users_custom_column( $row_output, $column_id_attr, $user ) { $date_format = 'Y/m/d \a\t g:i a'; $d1 = 0; switch ( $column_id_attr ) { case 'registration_date': $d1 = strtotime(get_userdata($user)->user_registered); break; case 'last_login_date': $session_tokens = get_user_meta( $user, 'session_tokens', true ); if (!empty($session_tokens)) { $d1 = max(array_column(array_values($session_tokens),'login')); } break; default: } if ($d1 > 0) { $d2 = new DateTime("@$d1"); return $d2->setTimezone(wp_timezone())->format($date_format); } return $row_output; } // make the registration date column sortable add_filter( 'manage_users_sortable_columns', 'my_manage_users_sortable_columns' ); function my_manage_users_sortable_columns( $columns ) { return wp_parse_args( array( 'registration_date' => 'registered', 'last_login_date' => 'Last Logged In' ), $columns ); } add_action( 'pre_user_query', 'misha_users_by_date_registered_by_default' ); function misha_users_by_date_registered_by_default( $query ) { global $pagenow; if ( is_admin() && 'users.php' == $pagenow ) { $query->query_orderby = 'ORDER BY user_registered DESC'; } return $query; } A: The default Last Login column only applies to users who are currently logged in. The timestamp is deleted when the user logs out. First, you need to save the timestamp when a user logs in. This will save it to user_meta. function save_login_timestamp( $user_login, $user ) { update_user_meta( $user->ID, 'last_login', time() ); } add_action( 'wp_login', 'save_login_timestamp', 10, 2 ); To sort by this value you need to add a column to the users table and make it sortable. // Add a new column to the users table function add_last_login_column( $columns ) { $columns['wfls_last_login'] = 'Logged In'; // give this one a more accurate title $columns['last_login'] = 'Last Logged In'; // add a new one return $columns; } add_filter( 'manage_users_columns', 'add_last_login_column' ); // Display the last_login time for each user in the new column function display_last_login_column( $value, $column_name, $user_id ) { if ( $column_name === 'last_login' ) { $last_login = get_user_meta( $user_id, 'last_login', true ); if ( $last_login ) { return date( 'Y/m/d H:i', $last_login ); } return 'Never'; } return $value; } add_filter( 'manage_users_custom_column', 'display_last_login_column', 10, 3 ); // Make the column sortable function make_last_login_column_sortable( $columns ) { $columns['last_login'] = 'last_login'; return $columns; } add_filter( 'manage_users_sortable_columns', 'make_last_login_column_sortable' ); // Sort the users by last_login function sort_by_last_login( $query ) { if ( $query->get( 'orderby' ) === 'last_login' ) { $query->set( 'meta_key', 'last_login' ); $query->set( 'orderby', 'meta_value_num' ); } } add_action( 'pre_get_users', 'sort_by_last_login' );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show entire post title without elipsis? I want to know how to show my post title without ellipsis. As you can see from the image below, the title is shorten for some reason. Any help would be appreciated. FYI, I don't write code so I need to know how to fix this issue without using code so I could use plugin but I can't edit PHP.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I customize sections of the homepage layout? I would like to customize sections of my site layout based on categories, what could be a quick fix? I show you an example site that inspires me:
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create a page for each database table entries I am creating a job board website(it is a part of the website). I have a JobOffer class with some rows in the database(added with it's form...). My problem now is to have a page for each of these JobOffers. I can't use it as a WP_Post because a want a custom rendering, i will need to add own data. This is my idea: * *Create a page(from the wordpress dashboard -> Pages) with the name "Job Offer" and slug "job-offer" *Set the link a JobOffer like /job-offer?id={job_id}&label={job_label} *In the "Job Offer" page only add this shotcode: [single-job-offer] *In the shortcode definition get the id ($_GET['id']) and the label($_GET['label']) and render the content as i want *Change the page url and page title in the browser with javascript: document.title = "The job title" window.history.pushState("url_with_a_better_form"); But it is not a good idea. Hoping i explain well what i want, what do you think i should do to follow SEO rules and have a page for all JobOffers, each of these pages having a title, a custom url and my shortcode as content. EDIT: I followed the links given and i created my custom post type: function phenix_custom_post_type() { register_post_type( 'phenix_job_offer', array( 'labels' => array( 'name' => 'Job Offers', 'singular_name' => 'Job Offer', ), 'public' => true, 'show_ui' => false, 'rewrite' => array( 'slug' => 'offres' ) ) ); } add_action('init', 'phenix_custom_post_type'); And my template(single-phenix_blue_color.php): <?php get_header(); do_action('onepress_page_before_content'); // I'm working in my child theme and the parent is OnePress ?> <div id="content" class="site-content"> <?php onepress_breadcrumb(); ?> <div id="content-inside" class="container "> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while (have_posts()) : the_post(); ?> <?php get_template_part('template-parts/content', 'single'); ?> <hr class="hr"> <?php if (is_user_logged_in() && in_array('subscriber', _wp_get_current_user()->roles)) : // if ($job_apps != null && count($job_apps) > 0) { $tmp = array_filter($job_apps, function (JobApplication $elt) { return is_int(strpos($_SERVER['REQUEST_URI'], $elt->job->post_name)); }); if (count($tmp) > 0) echo "<div class='mt-2 mb-3 h6'><span class='alert alert-info'>" . do_shortcode('[icon name="circle-info" prefix="fas"]') . " ...</span></div>"; } ?> <p class="h5 mb-3">...</p> <?= do_shortcode('[form-job-application]') ?> <?php else : ?> <p class="h6"> //// <?php if (!is_user_logged_in()) : ?> /////// <?php endif; ?> </p> <?php endif; ?> <?php endwhile; ?> </main> </div> </div> </div> <?php get_footer(); ?> Sorry for the length. I manually created a post in the database with the phenix_job_offer type and it displays well. I am still thinking on how i can more customize the template but my problem is: How can i tell the template to not try to fetch the post in the database but use my post(a custom wp_post that i will create just for the rendering of my JobOffer) ? A: WordPress does not work this way. At least it's not recommended to cook WordPress this way because it uses different concepts you won't see in most other CMS and frameworks. It'd be better to create a custom post type. In this case, your job offer postings permalinks will look like this: site.com/job-offfer/... In this case, you'll be able to use all the features that WordPress provides for custom post types: meta fields, template structure, etc. You can learn more about custom post types and how to handle them here: https://developer.wordpress.org/plugins/post-types/registering-custom-post-types/ https://developer.wordpress.org/plugins/post-types/working-with-custom-post-types/ https://developer.wordpress.org/themes/template-files-section/custom-post-type-template-files/ A: I resolve the problem. What have i done ? * *Create and register my custom post type, create a template for it (see my edit in the first message of the topic). *Create a small code that creates a post for each of my jobOffers with these fields: // I also add this function in the `JobOffer` creation function so that the new ones will have a corresponding post wp_insert_post([ 'post_content' => $jobOffer->description, 'post_title' => $jobOffer->label, 'post_excerpt' => substr($jobOffer->description, 75), 'post_type' => 'phenix_job_offer', 'post_name' => sanitize_title($jobOffer->label), 'meta_input' => ['job_offer' => $jobOfferId] ]); * *After that in my template i fetch the jobOffer with the post meta key ‘job_offer’ then render it as i want. $post = get_post(); require_once('wp-content/themes/PhenixDOr-Plus/includes/repositories/repository-job-offer.php'); $jobOfferRepo = new JobOfferRepository(); $jobOffer = $jobOfferRepo->get(intval($post->job_offer)); // My template
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My activator class isn't running the code inside I am using the WP Plugin Boilerplate and I am requiring files and admin notices within the activator class but my Kirki panel is not showing up in the customizer and the admin notice isn't appearing. I am also not getting any error messages. Also PLUGINPATH is set to plugin_dir_path( __FILE__ ). class Wp_Portfolio_Pro_Activator { /** * Short Description. (use period) * * Long Description. * * @since 1.0.0 */ public static function activate() { // Require Kirki and setting for plugin build on framework. self::load_files(); add_action( 'admin_notices', array( __CLASS__, 'admin_notice' ) ); } public static function admin_notice() { $message = '<div class="notice notice-success"><p>'; $message .= sprintf( __( 'Hello %s!', 'my-plugin' ), '<strong>' . get_current_user_name() . '</strong>' ); $message .= '</p><p>'; $message .= __( 'Thank you for downloading WP Portfolio Pro. Edit the setting from the customizer.', 'wp-portfolio-pro' ); $message .= '</p>'; $message .= '<a href="' . esc_url( admin_url( 'customize.php?customize_changeset_uuid=' . get_theme_mods_changeset_post_id() ) ) . '"><button>Go to settings</button></a></div>'; echo $message; printf( '<div class="notice notice-success is-dismissible">%1$s</div>', $message ); } public static function load_files() { // Require Kirki and setting for plugin build on framework. require_once PLUGINPATH . 'includes/kirki/kirki.php'; require_once PLUGINPATH . 'includes/wp-portfolio-pro-kirki.php'; } } This is the code in the main file that hooks into the activation hook. /** * The code that runs during plugin activation. * This action is documented in includes/class-wp-portfolio-pro-activator.php */ function activate_wp_portfolio_pro() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-wp-portfolio-pro-activator.php'; Wp_Portfolio_Pro_Activator::activate(); } /** * The code that runs during plugin deactivation. * This action is documented in includes/class-wp-portfolio-pro-deactivator.php */ function deactivate_wp_portfolio_pro() { require_once PLUGINPATH . 'includes/class-wp-portfolio-pro-deactivator.php'; Wp_Portfolio_Pro_Deactivator::deactivate(); } register_activation_hook( __FILE__, 'activate_wp_portfolio_pro' ); register_deactivation_hook( __FILE__, 'deactivate_wp_portfolio_pro' );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems Implementing Non-WordPress Rewrite Rules A colleague and I are working on a custom theme and one of the things we need to do is push a specific custom URL type (/team/ for example) into the backend of our website(/wp-content/themes/custom_theme/page-templates/team.php). We're trying to use url rewriting as described in this article. The theme's functions.php contains the following code, which we've proved is running (debug() does that). function themes_dir_add_rewrites() { $theme_name = next(explode('/themes/', get_stylesheet_directory()));   global $wp_rewrite; $new_non_wp_rules = array('team/.*'=> 'wp-content/themes/'. $theme_name . '/page-templates/team.php',); debug(print_r($new_non_wp_rules, true)."\n"); $wp_rewrite->non_wp_rules = array_merge($wp_rewrite->non_wp_rules,$new_non_wp_rules); } add_action('generate_rewrite_rules', 'themes_dir_add_rewrites'); We run this by going to the rewrite rules in the WordPress back-end and saving them. This runs the above code (debug() function call fires), and in theory and flushing/rewriting the rules. However, the redirect isn't working, and browsing to /team/ simply calls the 404.php page template instead of going where we want it to. We added some code to the 404.php page as follows to see if we can see anything: global $wp_rewrite; echo "<pre>"; print_r($wp_rewrite->non_wp_rules); print_r($wp_rewrite->rules); echo "</pre>"; ?> This duly prints out the two data structures, however $wp_rewrite->non_wp_rules is empty (null). $wp_rewrite->rules has all the usual wordpress defaults. We are running a DevKinsta development environment. Any pointers as to what might be going on, or even how to debug further would be most welcome. First step would seem to be getting an entry to stick in $wp_rewrite->non_wp_rules. Thanks in advance. Update: To explain further what we are doing... One of the theme settings pages in the back-end looks like this: We would like the theme user to be able to select between static pages which they create, or the 3 built-in pages we have in the theme for these functions. If the Theme Default is chosen in the drop-downs (see Customers above), then our url rewrites would apply and "/contact/", "/team/", and "/customers/" would render the respective built-in page without changing the url. A: Here's a solution to the problem. Not sure it's the best one, but it does work. From lots of reading and a bit of poking around in the wordpress core (code), it seems that non_wp rewrite rules only work on Apache. DevKinsta is Nginx-based, and there's precious little out there at this deep level on any of the tech blogs, stackExchange, or stackOverflow. Anyway, I ditched all the previous rewrite code and used the following instead: //catch "/contact/", "/customers/", and "/team/" in the URL and pull content from the built-in templates function templates_callback( $original_template ) { $theme_name = next(explode('/themes/', get_stylesheet_directory())); $url = $_SERVER['REQUEST_URI']; //FIXME the logic below needs to be extended to check for the dropdown setting of each page //in the themes setting page. If the setting is default, return the template as configured //below. If there's another page selected, return that page instead if (preg_match('/\/team\//',$url)) { return 'wp-content/themes/'. $theme_name . '/page-templates/team.php'; }elseif(preg_match('/\/contact\//',$url)){ return 'wp-content/themes/'. $theme_name . '/page-templates/contact.php'; }elseif(preg_match('/\/customers\//',$url)){ return 'wp-content/themes/'. $theme_name . '/page-templates/customers.php'; }else { return $original_template; } } add_filter( 'template_include', 'templates_callback' );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Backend working but not front I tried to move a site I was working on from my laptop to my desktop computer. Once I got some issues with the database sorted I managed to log into the admin. After updating everything that needed it I tried to look at the front end of the site and received the following error: The file wp-config.php already exists. If you need to reset any of the configuration items in this file, please delete it first. You may try installing now. I have installed WordPress dozens of times and never run into this before. I checked my wp-config.php file and didn't find any errors. I did a few other things, including doing multiple searches for the issue, and eventually deleted the database, downloaded a fresh copy of WordPress, and did a completely new install. Yet I still have the same problem. I know the most common reasons for this message are failure to connect to the database and having the wrong table prefix, but I have checked and re-checked those and they are fine. In fact, I did the "easy 5-minute install" to make sure there was no user error, so everything is at the WordPress defaults. What is really confusing is that the back end seems to work perfectly, but when I try to access the front end of the site it tries to go to /wp-admin/setup-config.php instead of the index.php. I know it runs an is_blog_installed function, but I didn't see what it was looking for. Is there something that didn't get done when the installation finished?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: hiddenQuestions.find is not a function I have a code like this: var hiddenQuestions = listQuestions.hidden_questions; var find = hiddenQuestions.find(function (questionId) { return parseInt(question.id) === parseInt(questionId); }); question.open = !find; return question; }) But it is giving me the below error on the console: Uncaught TypeError: hiddenQuestions.find is not a function Can anyone please point me what's wrong there? Thank you in Advance
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: May I know where to edit the tax rate? I'm newbie in Wordpress. Our company website using the shopper as theme. But where can I find this part and change it?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Number in Text domain I want to make a plugin for wordpress plugin repo. There are a number of plugins already in wp plugin repository of my niche. To avoid text domain confliction and unique text domain can I use number in text-domain? Suppose my text domain is 'example-plugin-801'.Is it valid text domain?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot attach custom taxonomy term to a custom post type. Post taxonomy terms are not saving I have a custom post type with five different custom taxonomies attached to it. Of those 5, I am unable to add taxonomy terms to posts. However, the other four taxonomies are saving just fine! Here is the definition of the custom taxonomy term in question: function taxonomy_country() { $labels = array( 'name' => _x('Countries', 'Countries'), 'singular_name' => _x('Country', 'Region'), 'search_items' => __('Search Countries'), 'all_items' => __('All Countries'), 'parent_item' => __('Parent Country'), 'edit_item' => __('Edit Country'), 'update_item' => __('Update Country'), 'add_new_item' => __('Add New Country'), 'new_item_name' => __('New Country Name'), 'menu_name' => __('Countries'), ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'show_ui' => true, 'show_in_rest' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array('slug', 'country'), ); register_taxonomy('country', array('bird'), $args); } add_action('init', 'taxonomy_country'); Whether I select one or more terms or I add one on the fly, after saving the post, they don't get associated with the posts. If I add one taxonomy terms on the fly while editing a post, it is getting added to the database fine but not being associated to the post!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: upload image to wordpress media library failed for custom post type image upload failed. I tried to upload gym logo as thumbnail image for gym post type. All the form elements are working. But image upload is not working. images are not appearing in WordPress media library. Help Me to find error in my code. ''' add_shortcode( 'gym_submission_form', 'gym_submission_form_shortcode' ); ob_start(); function gym_submission_form_shortcode() { if ( isset( $_POST['submit_gym'] ) ) { // Sanitize and validate form data $gym_name = sanitize_text_field( $_POST['gym_name'] ); $gym_address = sanitize_text_field( $_POST['gym_address'] ); $gym_phone = sanitize_text_field( $_POST['gym_phone'] ); $gym_district = sanitize_text_field( $_POST['gym_district'] ); $gym_thana = sanitize_text_field( $_POST['gym_thana'] ); $gym_slogan= sanitize_text_field( $_POST['gym_slogan'] ); // 2 variable for checkbox group saving // Get the selected payment methods as an array . if payment method selected take array if not ampty $payment_methods = isset( $_POST['gym_payment'] ) ? $_POST['gym_payment'] : array(); // Convert the array to a string separated by a delimiter $payment_methods_string = implode( '|', $payment_methods ); // sanitize and validate the file input before processing it: if ( isset( $_FILES['gym_logo'] ) && ! empty( $_FILES['gym_logo']['name'] ) ) { $allowed_types = array( 'jpg', 'jpeg', 'png', 'gif' ); $uploaded_file = $_FILES['gym_logo']; // Sanitize the file name $sanitized_file_name = sanitize_file_name( $uploaded_file['name'] ); // Validate the file type $uploaded_file_type = wp_check_filetype( $sanitized_file_name, $allowed_types ); if ( ! $uploaded_file_type['ext'] || ! $uploaded_file_type['type'] ) { // Invalid file type wp_die( 'Invalid file type.' ); } // Validate the file size $max_file_size = wp_max_upload_size(); if ( $uploaded_file['size'] > $max_file_size ) { // File size too large wp_die( 'File size too large.' ); } // Move the file to the uploads directory $upload_dir = wp_upload_dir(); $file_name = wp_unique_filename( $upload_dir['path'], $sanitized_file_name ); $file_path = $upload_dir['path'] .'/'. $file_name; move_uploaded_file( $uploaded_file['tmp_name'], $file_path ); } // Create the new gym post $new_gym = array( 'post_title' => $gym_name, 'post_content' => '', 'post_status' => 'draft', 'post_type' => 'gym', ); $new_gym_id = wp_insert_post( $new_gym ); // Save meta data if ( $new_gym_id ) { update_post_meta( $new_gym_id, 'gym_address', $gym_address ); update_post_meta( $new_gym_id, 'gym_phone', $gym_phone ); update_post_meta( $new_gym_id, 'gym_district', $gym_district ); update_post_meta( $new_gym_id, 'gym_thana', $gym_thana ); update_post_meta( $new_gym_id, 'gym_slogan', $gym_slogan ); update_post_meta( $new_gym_id,'gym_payment', $payment_methods_string); update_post_meta( $new_gym_id, '_thumbnail_id', $file_path ); } // Redirect the user to the thank you page wp_redirect( '/thank-you/' ); exit; } // Display the gym submission form ?> <form method="post"> <label for="gym_logo">Gym Logo:</label> <input type="file" name="gym_logo" id="gym_logo" accept="image/*" required> <label for="gym_name">Gym Name:</label> <input type="text" name="gym_name" required> <label for="gym_address">Gym Address:</label> <input type="text" name="gym_address" required> <label for="gym_phone">Gym Phone:</label> <input type="tel" name="gym_phone" required> <label for="gym_district">Select a district:</label> <select id="district" name="gym_district" onchange="populateThana()" required> <option value="">Choose a district</option> <option value="Dhaka">Dhaka</option> <option value="Chittagong">Chittagong</option> </select> <label for="gym_thana">Select a thana:</label> <select id="thana" name="gym_thana" required> <option value="">Choose a thana</option> </select> <label for="gym_slogan">Slogan:</label> <input type="text" name="gym_slogan" id="gym_slogan" required> <label for="gym_payment">Payment Method:</label> <input type="checkbox" id="mobile_payment" name="gym_payment[]" value="Mobile Payment"> Mobile Payments<br> <input type="checkbox" id="cash" name="gym_payment[]" value="Cash">cash<br> <input type="checkbox" id="credit_cards" name="gym_payment[]" value="Credit Cards"> credit cards <input type="submit" name="submit_gym" value="Submit"> </form> <?php return ob_get_clean();}
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Admin Notice is only localized when displaying the "Plugins" Backend Page My plugin checks if a specific theme is activated. The check is hooked on init. If the theme is not activated, it displays a warning, hooked on admin_notices. This works fine. Now I added localization support with the help of "Loco Translate" and .mo / .po files. load_plugin_textdomainis hooked on init. This works too, translations are showing up. Now it gets weird: My "Admin Notice" gets translated as expected, but only when opening wp-admin/plugins.php. On any other backend-page the non-translated version appears. My guess is it has something to do with the hook-order, but I can not figure out how to order the checks properly. Some code, redacted for sanity: <?php namespace Me\MyPlugin; class Bootstrapping { public static function notifyOnMissingTheme(): void { if( ! self::ThemeIsActivated() ) { add_action('admin_notices', [self::class, '_echoThemeExistanceWarning']); } } public static function activateTranslationSupport() : void { load_plugin_textdomain( 'language-domain', false, dirname(plugin_basename(__FILE__)) . '/languages'); } private static function ThemeIsActivated(): bool { $theme = wp_get_theme(); if (!('My themes name' == $theme->name || 'My themes name' == $theme->parent_theme) ) { return false; } return true; } static function _echoThemeExistanceWarning(): void { echo '<div class="notice notice-warning"><p>'. __('Notification from Plugin: Please activate the Theme for best experience with this plugin!', 'language-domain'). '</p></div>'; } } <?php /* Plugin Name: Plugin Text Domain: language-domain Domain Path: /languages */ namespace Me\MyPlugin; add_action('init', [Bootstrapping::class, 'activateTranslationSupport']); add_action('init', [Bootstrapping::class, 'notifyOnMissingTheme']); Two screenshots for clarification: Thanks alot for your help! A: Note: Revised because that '__FILE__' as in dirname(plugin_basename('__FILE__')), was just a typo in the post/question. But one thing you did not include in your post, is about how are you loading the Bootstrapping class, and where is the file located? Is it in a subfolder like includes, i.e. your-plugin/ includes/ class-bootstraping.php languages/ your-plugin.pot your-plugin.php (main plugin file) If so, then you should not use __FILE__ and instead, in the main plugin file, you can define a constant which stores the full absolute path to the main plugin file. E.g. define( 'YOUR_PLUGIN_FILE', __FILE__ ); // I commented it out, but this is how I loaded the class: //require_once __DIR__ . '/includes/class-bootstraping.php'; Then from within your class, when you call plugin_basename(), pass the above constant. E.g. load_plugin_textdomain( 'language-domain', false, dirname( plugin_basename( YOUR_PLUGIN_FILE ) ) . '/languages' );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multi color post title by using custom javascript inside the gutenberg editor? I'm just getting started with the gutenberg editor. I want the editing person to be able to select parts of the post title wich then opens a toolbar above the selected textpart letting you choose a color from the color palette. The idea is to then wrap the selected text part in, idk, html-comments or maybe spans directly to set the color. The problem is the only thing I know is how I can enqueue javascript for the backend so it is available in my gutenberg editor. But how would I go about this? There is the Javascript 'wp'-object which might be helpful? I don't really find any resources that show how something similar to what i described above works.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change the default location where new post gets stored? Traditionally, in WordPress after we write a new post it is stored in the location (URL) as followed: www.mysite.com / best-headphones-of-2023 But what if we want to store that new post after one more hierarchy like: www.mysite.com / blog / best-headphones-of-2023 Please note that here I'm not talking about creating a category page and then posting that link on the homepage. How to achieve this? And which particular setting needs to be tweaked? A: I would look in permalink settings in your wp-admin dashboard. That's where you can alter url structures of your WordPress site including how post urls are determined. I think that's all you would need depending on your theme.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: footer doesn't display I'm trying to code in the file index.php, but the footer and the slider that is in the content.php file don't display. index.php code: <?php get_header(); if (have_posts()) : while (have_posts()) : the_post(); get_template_part('content', get_post_format()); endwhile; else: get_template_part('content'); endif; get_footer(); ?> footer.php : <footer> <div class="footer-content"> <img class="logo" src="ressources/logoge.png" alt="logo AEG"> <div class="contact"> <h3>Contact</h3> <p>Lorem ipsum dolor sit amet, <br> consectetuer adipiscing elit,sed diam nonummy nibh</p> </div> <div class="conditions"> <h3>Conditions generales</h3> <p>Lorem ipsum dolor sit amet, <br> consectetuer adipiscing elit, sed diam nonummy nibh</p> </div> <div class="rss"> <h3>Reseaux sociaux</h3> <button> <img src="ressources/iicon.png"> </button> <button> <img src="ressources/ficon.png"> </button> <button> <img src="ressources/ticon.png"> </button> </div> </div> <?php wp_footer(); ?> </footer> </body> </html> content.php: <!-- Slideshow container --> <div class="slideshow-container"> <!-- Full-width images with number and caption text --> <div class="mySlides fade"> <img src="ressources/walpaper9.jpeg" style="width:1000px"> <div class="slide-text"> <p>Lorem ipsum dolor sit amet</p> <h2>AEG TEST</h2> </div> </div> <div class="mySlides fade"> <img src="ressources/walpaper6.jpeg" style="width:1000px"> <div class="slide-text"> <p>Lorem ipsum dolor sit amet</p> <h2>AEG TEST</h2> </div> </div> <div class="mySlides fade"> <img src="ressources/walpaper2.jpeg" style="width:1000px"> <div class="slide-text"> <p>Lorem ipsum dolor sit amet</p> <h2>AEG TEST</h2> </div> </div> <!-- Next and previous buttons --> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> </div> <br> <!-- The dots/circles --> <div style="text-align:center"> <span class="dot" onclick="currentSlide(1)"></span> <span class="dot" onclick="currentSlide(2)"></span> <span class="dot" onclick="currentSlide(3)"></span> </div> <div class="archives-container"> <div class="archives"> <div class="archives-preview"> <h2>Base de données ADHEMAR et <br> archives numerisées</h2> </div> <div class="archives-btn"> <button class="btn">Archives online</button> </div> </div> </div> <div class="newsletter-container"> <div class="newsletter"> <div class="newsletter-preview"> <h2>Newsletter</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, <br> sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna </p> </div> <div class="newsletter-btn"> <input class="lbl" type="text" id="textlabel" placeholder ="Nom,Prenom"> <input class="lbl" type="email" id="emaillabel" placeholder="email"> </div> </div> </div> <div class="archives-v2"> <h2>Base de données ADHEMAR et <br> archives numerisées </h2> <div class="btnarchive"> <button class="btn-archives-v2">Archives online</button> </div> </div> <div class="newsletter-v2"> <h2>Newsletter</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, <br> sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna </p> <input class="lbl" type="text" id="textlabel" placeholder ="Nom,Prenom"> <input class="lbl" type="email" id="emaillabel" placeholder="email"> </div> <div class="container-grid"> <img src="ressources/wallpaper1.jpeg"> <img src="ressources/walpaper2.jpeg"> <img src="ressources/walpaper4.jpeg"> <img src="ressources/walpaper4.jpeg"> <img src="ressources/walpaper6.jpeg"> <img src="ressources/walpaper2.jpeg"> <img src="ressources/walpaper8.jpeg"> <img src="ressources/walpaper9.jpeg"> <img src="ressources/walpaper10.jpg"> <img src="ressources/walpaper11.jpeg"> <img src="ressources/walpaper6.jpeg"> <img src="ressources/walpaper9.jpeg"> </div> <?php wp_content(); ?> <script> let slideIndex = 1; showSlides(slideIndex); // Next/previous controls function plusSlides(n) { showSlides(slideIndex += n); } // Thumbnail image controls function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { let i; let slides = document.getElementsByClassName("mySlides"); let dots = document.getElementsByClassName("dot"); if (n > slides.length) { slideIndex = 1 } if (n < 1) { slideIndex = slides.length } for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className.replace(" active", ""); } slides[slideIndex-1].style.display = "block"; dots[slideIndex-1].className += " active"; } </script> After a lot of modifications trying to find what is wrong, when I inspect the page, I can not see the footer.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Count the number of matching post names in foreach loop I have a simple foreach loop that outputs an ordered list from a CPT 'post_subscribers' and an associated meta key called 'project'. $theposts = get_posts( array( 'post_type' => 'post_subscriber', 'post_status' => 'publish', 'numberposts' => -1, ) ); echo '<ol>'; foreach( $theposts as $p ): $project_name = get_post_meta($p->ID, 'project', true); echo '<li class="mb-3">'; echo get_the_title($project_name); echo '</li>'; endforeach; echo '</ol>'; echo 'Total projects - '. count($theposts)."</br>"; My list will generate: * *Project title one *Project title two *Project title two *Project title two *Project title three *Project title one Total projects - 6 Q) Within my generated ordered list there are several exact matching '$project_name'(s). How can I count the multiple matching '$project_name' entries and display the count for each of them as separate results? (As I have 300+ in my generated list). EG result: There are 3 projects with the name 'Project title two'. It seems like a relatively simple task but I can't get my head around it? Many thanks in advance :-) A: I would get the count of a variable number of repeated titles by using an indexed array. $theposts = get_posts( array( 'post_type' => 'post_subscriber', 'post_status' => 'publish', 'numberposts' => -1, ) ); // project titles counter, outside the loop $project_titles = array(); foreach( $theposts as $p ): $project_name = get_post_meta($p->ID, 'project', true); echo '<ol>'; echo '<li class="mb-3">'; $project_title = get_the_title($project_name); echo $project_title; // check if $project_titles contains $project_title already if ( array_key_exists( $project_title, $project_titles) ) : $project_titles[$project_title]++; else : // otherwise, initialize key value pair with 1 $project_titles[$project_title] = 1; endif; echo '</li>'; echo '</ol>'; endforeach; // loop through and print all foreach ($project_titles as $project_title => $project_title_count) : if ($project_title_count > 1) : // repeated echo 'There are ' . $project_title_count . ' projects with the name ' . $project_title . '.<br/>'; endif; endforeach; $project_titles will now store the number of times each title is repeated as a key-value pair. The key will be your project's title, and the value will be the number of times that project's title exists. EDIT: Removed first code block since it wasn't useful with question update. Updated second block of code to accommodate a variable number of repeated titles.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Possible SQL injection. How to locate and fix? Google Search Console is saying that certain suspicious URLs in my site are returning a 403 error. They look exactly like this (the links below are not my sites, just examples): https://www.languagetesting.com/catalogsearch/result/?q=free%20url%20indexer%2C%E3%80%90Visit%20Sig8%2Ecom%E3%80%91backlinksindexer%20review%2CLinks%20Indexer%2Cindexer%20url%2Curl%20index%20checker%2CCheapest%20price%20and%20fast%20index%2Cbacklink%20indexer%20online%20free%2Cgoogle%20url%20index%20tool%2Cbacklinks%20indexer%20review%2CUrl%20Indexer%2Cfast%20backlink%20indexing%2C....3605 and https://www.flykolibri.com/catalogsearch/result/?q=coins%20fc%2024%20xbox%2C%E3%80%90Visit%20Coinsnight%2Ecom%E3%80%91fc%2024%20coins%20g2a%2Cfc%2024%20promotion%20coins%2Cfc%20coins%20pc%2Cfc%20coins%2024%20buy%2Cfc%20coins%20safe%20to%20buy%2C....72a7 A quick Google search for "sig8" and "coinsnight" reveals that many sites are affected by this. I am guessing it's some kind of SQL injection. How do I go about finding and removing this in my Wordpress instance? I did a mysqldump of the database and searched for those domains (sig8, coinsnight, they are the same in my blocked URLs), just to try to locate the post or entry, but it doesn't find anything. On my site, all pages affected are search pages. They look like this: domain.com/?s=coins%20fc%2024%20xbox%2C%E3%80%90Visit%20Coinsnight%2Ecom%E3%80%91fc%2024%20coins%20g2a%2Cfc%2024%20promotion%20coins%2Cfc%20coins%20pc%2Cfc%20coins%2024%20buy%2Cfc%20coins%20safe%20to%20buy%2C....72a7
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not getting expected email when running cron hook I'm following the tutorial at https://wpshout.com/wp_schedule_event-examples/ I want to ensure my cron job works and is run at approximately a certain time of day. I have inserted debug code to send an email into the code: // Schedule daily event at specific time function daily_event_hook() { $headers = array('Content-Type: text/plain; charset=UTF-8'); $succ = wp_mail( '[email protected]', 'Testing', 'This is a test', $headers ); wp_schedule_event( strtotime('13:43'), 'daily', 'run_daily_event' ); } add_action( 'wp', 'daily_event_hook' ); function run_daily_event() { $headers = array('Content-Type: text/plain; charset=UTF-8'); $succ = wp_mail( '[email protected]', 'Running cron!', 'cron ran', $headers ); } The time in strtotime is set a few minutes ahead of my current time. I receive an email when the daily_event_hook function is run when the cron job is scheduled. So I know that's working. But when I hit a page on the site after that time, I get no eamil from the run_daily_event hook. The code looks good as far as I can tell. I've tried setting the time to both local time and GMT. I'm wondering if the wp_mail function is loaded when running cron. If so, how can I load it? If it is loaded, what's wrong with my code? I need the run_daily_event hook to send email notifications to actual users so sending the email this isn't just for testing purposes.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what did I do wrong after click event? jQuery(document).ready(function($) { $('a[data-acf]').click(function(event) { event.preventDefault(); var field_name = $(this).data('acf'); var field_value = get_field('km1'); if (field_value) { var form_id = $(this).closest('form').attr('id'); var input_name = $('text-639' + form_id + ' input[name="text-639"]'); input_name.val(field_value); // qui puoi ripetere le righe precedenti per altri campi del modulo CF7 } $(this).closest('form').submit(); }); }); I am trying to call up my customfields in my form after clicking on the link but my code does not return any values where did I go wrong?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do i change style of specific radio button label from Contact Forms 7 plugin based off data retrieved from API endpoint? sorry if this is a basic question or something easy, but I've tried searching online and I wasn't able to find solutions, and I'm also new to Wordpress. Perhaps I hadn't search properly, but thought I could try asking it here. I'm retrieving a piece of data from an API endpoint called 'heartTypes' for example using a custom plugin. I'm then returning it through a shortcode which gives the result "WEAK". There are 4 heart types, WEAK, SLIGHTLY WEAK, PASSABLE, STRONG. How do I only make the WEAK radio button label have a different border color after retrieving it from the API endpoint by integrating it from the radio button from contact forms? If the shortcode returned PASSABLE, only the PASSABLE radio button label would have a highlighted border and so on. Or a different plugin is fine too, but I'm slightly lost on what path I should now be taking. Any help or insights would be appreciated!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use a conditional statement in a post loop but not count towards the "posts_per_page" if false I have a WP_Query which has the "posts_per_page" parameter set to 12. I am then using a while loop to iterate over all of the posts and an IF statement to check whether a condition is true or false. I would like to be able to display 12 posts which return true however, the loop is obviously also counting each post returning false and displaying nothing. For example, 5 posts would be displayed but the other 7 are not displayed. $args = array( 'post_type' => $post_slug, 'posts_per_page' => 12, 'paged' => 1, 'post_status' => 'publish', ); $topicsHub = new WP_Query($args); <?php while ( $topicsHub->have_posts() ) : $topicsHub->the_post(); $resource_type = get_post_type(); if($resource_type == 'tools') { $stream = get_field('stream_name', get_the_ID()); $tooltype = get_field('tools_type', get_the_ID()); $stream_name = $stream; foreach ($options['streams'] as $key => $subscription) { if(in_array($subscription['parent_stream_name'], $stream)){ $stream_name = []; $stream_name[] = $subscription['name']; break; } } // Custom function if(check_if_user_has_access($stream_name, 'something')) { if($tooltype == 'free') { continue; } } else { if($tooltype == 'premium') { continue; } } } ?> <div class="u-12 u-6@sm u-4@md resource__main-tab--item"> <?php get_template_part('partial/content', 'topics-card'); ?> </div> <?php endwhile; ?> I understand why this is happening but am not sure how I could only show 12 posts that only return true. A: The simplest solution would be to query all posts using a -1 in place of the 12 in your 'posts_per_page' argument of your query. Then use a counter that ticks up if all of the above conditions equal true. $args = array( 'post_type' => $post_slug, 'posts_per_page' => -1, 'paged' => 1, 'post_status' => 'publish', ); $topicsHub = new WP_Query($args); $post_counter = 0; <?php while ( $topicsHub->have_posts() ) : $topicsHub->the_post(); // if the $post_counter variable gets above your limit, break from the loop if ($post_counter >= 12) { break; } // conditional statements, breaks and continues... ?> <div class="u-12 u-6@sm u-4@md resource__main-tab--item"> <?php get_template_part('partial/content', 'topics-card'); ?> </div> <?php // increment $post_counter every time the loop gets this far (the above div will have printed) $post_counter++; endwhile; ?> However, if you wanted to query only the first 12 posts that matched your conditions, take a look at advanced query parameters for WP_Query($args). There are tons of IFs, ORs, XORs, etc. that you can use inside of the $args variable. Just might get super messy and unreadable with the amount of logic you're using in your while statement, so I'd recommend using the first method. A: I ran into a similar issue myself recently. I was trying to modify the search results with specific criteria being met. What I eventually did is modify the Query itself rather than trying to do that after the fact. I am not sure what your custom function does so I can't say for sure if this would work for you but here's how I would alter the query using metadata before displaying it. See this doc (I am assuming the get_field function is coming from acf and you can do this with acf fields) : $args = array( 'post_type' => $post_slug, 'posts_per_page' => 12, 'paged' => 1, 'post_status' => 'publish', 'meta_query' => array( array( 'key' => 'tooltype', 'value' => array( 'free', 'premium') 'compare' => 'LIKE', ), array( 'key' => 'stream_name', 'value' => array( 'something'), 'compare' => 'LIKE', ), ), ); Then you would only get posts that match that criterion rather than doing it after the fact. I can also see that it's possible your code might be trying to limit what is available based on user meta. So another approach would be to alter the output template file (topics-card) instead and add a disabled attribute that disables the link to the posts or alter the HTML so that the post is not a link that doesn't match the criteria for access using the same functions your are using now. That way you don't have to mess with pagination or the query at all.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tab Nav and WordPress Settings API I created a settings page for my custom theme on WordPress and created the various metaboxes via Settings API. To try to keep the page neater I created Nav Tabs, the only problem is that I can only save the metaboxes in the first section. This is my code form: <?php // Check user capabilities if (!current_user_can('manage_options')) { return; } ?> <div class="wrap"> <?php settings_errors(); ?> <h1><?php echo esc_html(get_admin_page_title()); ?></h1> <form method="post" action="options.php" enctype="multipart/form-data"> <?php // Gestisce le tab di impostazione del tema $active_tab = "primary-colors-options"; if (isset($_GET["tab"])) { if ($_GET["tab"] == "primary-colors-options") { $active_tab = "primary-colors-options"; settings_fields("heisenberg_sezione_colori_primari"); } else if ($_GET["tab"] == "neutral-colors-options") { $active_tab = "neutral-colors-options"; settings_fields("heisenberg_sezione_colori_neutrali"); } else if ($_GET["tab"] == "header-options") { $active_tab = "header-options"; settings_fields("heisenberg_header_options"); } else if ($_GET["tab"] == "footer-options") { $active_tab = "footer-options"; settings_fields("heisenberg_footer_options"); } else { $active_tab = "404-options"; settings_fields("heisenberg_404_options"); } } ?> <h2 class="nav-tab-wrapper"> <a href="?page=heisenberg-options&tab=primary-colors-options" class="nav-tab <?php if ($active_tab == 'primary-colors-options') { echo 'nav-tab-active'; } ?> "><?php _e('Colori Primari', THEME_TEXT_DOMAIN); ?></a> <a href="?page=heisenberg-options&tab=neutral-colors-options" class="nav-tab <?php if ($active_tab == 'neutral-colors-options') { echo 'nav-tab-active'; } ?> "><?php _e('Colori Neutrali', THEME_TEXT_DOMAIN); ?></a> <a href="?page=heisenberg-options&tab=header-options" class="nav-tab <?php if ($active_tab == 'header-options') { echo 'nav-tab-active'; } ?> "><?php _e('Header', THEME_TEXT_DOMAIN); ?></a> <a href="?page=heisenberg-options&tab=footer-options" class="nav-tab <?php if ($active_tab == 'footer-options') { echo 'nav-tab-active'; } ?>"><?php _e('Footer', THEME_TEXT_DOMAIN); ?></a> <a href="?page=heisenberg-options&tab=404-options" class="nav-tab <?php if ($active_tab == '404-options') { echo 'nav-tab-active'; } ?>"><?php _e('404', THEME_TEXT_DOMAIN); ?></a> </h2> <?php do_settings_sections('heisenberg-options'); submit_button(); ?> </form> </div> This is my code for Settings API: <?php /*------------------------------- * WordPress Settings API -------------------------------*/ if (!isset($_GET["tab"]) || $_GET["tab"] == "primary-colors-options") { add_settings_section( 'heisenberg_sezione_colori_primari', __('Colori Primari', THEME_TEXT_DOMAIN), 'display_heisenberg_general_options_content', 'heisenberg-options' ); function display_heisenberg_general_options_content() { echo '<p>' . __('Lorem Ipsum.', THEME_TEXT_DOMAIN) . '</p>'; } add_settings_field( 'colore_primario_1', __('Colore Primario 1', THEME_TEXT_DOMAIN), 'colore_primario_1_callback', 'heisenberg-options', 'heisenberg_sezione_colori_primari' ); register_setting( 'heisenberg_sezione_colori_primari', 'colore_primario_1' ); function colore_primario_1_callback() { $colore_primario_1 = get_option('colore_primario_1'); if (isset($colore_primario_1) && $colore_primario_1 != '') { $colore_primario_1 = esc_attr($colore_primario_1); } else { $colore_primario_1 = '#05400A'; } echo "<input type='text' name='colore_primario_1' id='colore_primario_1' value='" . $colore_primario_1 . "' class='color-picker' data-alpha-enabled='true' />"; } } elseif ($_GET["tab"] == "neutral-colors-options") { add_settings_section( 'heisenberg_sezione_colori_neutrali', __('Colori Neutrali', THEME_TEXT_DOMAIN), 'display_heisenberg_colori_neutrali_options_content', 'heisenberg-options' ); function display_heisenberg_colori_neutrali_options_content() { echo '<p>' . __('Lorem Ipsum.', THEME_TEXT_DOMAIN) . '</p>'; } add_settings_field( 'colore_neutrale_1', __('Colore Neutrale 1', THEME_TEXT_DOMAIN), 'colore_neutrale_1_callback', 'heisenberg-options', 'heisenberg_sezione_colori_neutrali' ); register_setting( 'heisenberg_sezione_colori_neutrali', 'colore_neutrale_1' ); function colore_neutrale_1_callback() { $colore_neutrale_1 = get_option('colore_neutrale_1'); if (isset($colore_neutrale_1) && $colore_neutrale_1 != '') { $colore_neutrale_1 = esc_attr($colore_neutrale_1); } else { $colore_neutrale_1 = '#000'; } echo "<input type='text' name='colore_neutrale_1' id='colore_neutrale_1' value='" . $colore_neutrale_1 . "' class='color-picker' data-alpha-enabled='true' />"; } } Thank you to those who will help out! A: I solved it by changing the group name to each section by following this article: https://code.tutsplus.com/tutorials/the-wordpress-settings-api-part-5-tabbed-navigation-for-settings--wp-24971
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }