text
stringlengths 12
210k
| meta
dict |
---|---|
Q: How to get the last date updated of postmeta? I would like to know if have a way to get the last modified of a postmeta table. I tried to see in database, however I did not see a column with date last modified.
A: No
WordPress does not track that information. You can't find it because it does not exist.
Unless you specifically wrote code to track when post meta was added/modified, that information doesn't exist, and it's rare that any plugin would implement this as it would result in a lot of data collection.
It would also be obvious where that data was when looking at the database via PHPMyAdmin, which I and yourself did not see in the screenshot. So this data was never recorded, does not exist, and cannot be used. It would be a fools errand to continue the search.
The best hope you have is to check backups of your site and compare them by date to get a rough estimate of how far back the data existed. Emails/receipts/invoices might also corroborate this, but nothing in WordPress exists to tell you when a post meta was created or last modified.
The only other thing, is the post creation date, the post meta creation date must be the same or newer, but not older.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I'm building a WordPress theme and noticed that the 404 page template runs along with the corresponding templates for each page. Any idea why? function debug($message){
error_log($message, 3, get_template_directory() . '/debug.log');
}
I added the above function to each of the templates.
For example, front-page.php includes a line that goes like this: debug("front-page.php \n");
I use tail -f debug.log in the terminal to determine which templates are being used by a particular page.
Here is the result.
A: I used the following function to retrieve the URLs of each page.
function template_debug($filename = null) {
$url = home_url($_SERVER['REQUEST_URI']);
debug("Called from: $filename using URL $url \n");
}
Then I inspected the front page which triggered the 404 template along with the front-page template. The Network Monitor tab showed the error, which was an incorrect folder name included in the CSS file.
After making the necessary changes, the 404 template isn't being triggered anymore.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't retrieve user email address with REST API I would like to retrieve the email address of an user by id with the REST api from Python. The problem is I don't get the email in the JSON from the two calls I added below. Based on the docs it should be correct with the edit context, but unfortunately I get back a 403 error when I call the /wp-json/wp/v2/users/1/?context=edit. As I am new to WP development, I would really appreciate if somebody could show me what am I doing wrong. Or any other solution to get the emails with REST.
wordpress_user = "username"
wordpress_password = "pass"
wordpress_credentials = wordpress_user + ":" + wordpress_password
wordpress_token = base64.b64encode(wordpress_credentials.encode())
wordpress_header = {'Authorization': 'Basic ' + wordpress_token.decode('utf-8')}
# version
api_url = '.../wp-json/wp/v2/users/1/'
response = requests.get(api_url)
response_json = response.json()
print (response_json)
# version 2
api_url = '.../wp-json/wp/v2/users/1/?context=edit'
response = requests.get(api_url)
response_json = response.json()
print (response_json)
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Image in binary in the data to WordPress media library A specific API, returns an image in binary in the data.
If I need to save it to the server, I can easily do it by following the code.
$response = curl_exec($curl); // This is the API response
file_put_contents('example2.png', $response);
How can I add it to the WordPress media library?
A: You should use media_handle_sideload. Write your file out to the filesystem then use media_handle_sideload to process it in the same way any other upload is processed. Be sure to cleanup afterwards.
See: https://developer.wordpress.org/reference/functions/media_handle_sideload/#comment-983 for an example
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I package and distribute my WordPress plugin via git? I wrote a custom plugin for saving an uploaded .xlsx file to a .csv file. The code required an outside library and I used composer to install the code into my plugin's directory. So now I have this composer.json file in my plugin directory:
{
"require": {
"phpoffice/phpspreadsheet": "^1.27"
}
}
I also used wp-cli to generate the skeleton for the plugin. This added some files and directories for testing the plugin like bin, tests and phpunit.xml.dist. I haven't written any tests for the plugin yet though I may write some after I refamiliarize myself with writing tests for WordPress (it's been a while).
So I now want to push the module out from my devel machine and try it out on a staging server. WordPress/PHP development is not something I do that often. So I'm a little uncertain on how to accomplish. My specific questions are:
*
*What should I put in my .gitignore file?
*Am I even using composer properly? Does the vendor directory and composer.json file even belong in the plugin directory? This doesn't feel right to me but I'm not very familiar with composer and how it is intended to be used.
*Is there some mechanism for automating the installation of the library file provided by composer on the staging server? Or is that just something I have to take care of myself? I don't think the staging server even has composer installed on it.
Hopefully these are good questions and I'm not out to lunch. If I am or if there is anything else I need to consider, I'd appreciate a clue.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The wpmu_blogs_columns filter is not working I want to add an additional column in the multisite Sites page (sites.php). Found this code on this SO:
add_filter('wpmu_blogs_columns', 'xx_add_expired_date_column');
function xx_add_expired_date_column($site_columns) {
$site_columns['expired_Date'] = 'Expires';
return $site_columns;
}
/* Populate site_name with blogs site_name */
add_action('manage_sites_custom_column', 'xx_exipred_date_data', 10, 2);
function xx_exipred_date_data($column_name, $blog_id) {
$current_blog_details = get_blog_details(array('blog_id' => $blog_id));
echo ucwords($current_blog_details->blogname);
}
The wpmu_blogs_columns filter should add the additional column on the Sites screen. I put this code in a plugin I am developing. Other functions of that plugin are working properly. The plugin has been network activated.
When I look at the Sites list (Network Admin, Sites, or via the Network dashboard Sites, All Sites), the extra column is not there.
If I put a die() statement after the xx_add_expired_date_column function, that 'die' never happens.
I think it may be a loading sequence error - maybe the plugin is not being loaded on the Sites page? What can be done to enable this additional column?
Added 7 Feb 2023
Further testing: the wpmu_blogs_columns filter will work in the theme's (or Child Theme's) functions.php file, but not in a plugin.
Added 8 Feb 2023
As mentioned in the soon-to-be-accepted answer, the column array is $sites_columns (plural 'sites'). And the $column_name is important. The code in the answer will work.
A: I tested your code, fixing the $colum_name issue and it works ok for me.
add_filter('wpmu_blogs_columns', function ($site_columns) {
$site_columns['expired_Date'] = 'Expires';
return $site_columns;
});
add_action('manage_sites_custom_column', function ($column_name, $blog_id) {
if ( 'expired_Date' === $column_name ){
$current_blog_details = get_blog_details(array('blog_id' => $blog_id));
// do_action( 'qm/debug', ['Details:', $current_blog_details ] );
echo ucwords($current_blog_details->last_updated);
}
}, 10, 2);
You have to check the $column_name otherwise the echo will print in all custom columns.
Both the filter and the action are pretty specific, they will only run on the page /wp-admin/network/sites.php and nowhere else.
I tried the code above using Snippets plugin and also as a mu-plugin and both worked the same, haven't tried as a plugin (maybe you can wrap everything inside a add_action('plugins_loaded', function(){}); hook).
The qm/debug is for the plugin Query Monitor, a must-have for WP devs :)
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Problem moving to category posts page I want to edit the following code and when one of the options in is selected, it will refer to that page (with java code)
<?php
/*
Plugin Name: List Category Posts - Template "Default"
Plugin URI: http://picandocodigo.net/programacion/wordpress/list-category-posts-wordpress-plugin-english/
Description: Template file for List Category Post Plugin for Wordpress which is used by plugin by argument template=value.php
Version: 0.9
Author: Radek Uldrych & Fernando Briano
Author URI: http://picandocodigo.net http://radoviny.net
*/
/**
* The format for templates changed since version 0.17. Since this
* code is included inside CatListDisplayer, $this refers to the
* instance of CatListDisplayer that called this file.
*/
/* This is the string which will gather all the information.*/
$lcp_display_output = '';
// Show category link:
$lcp_display_output .= $this->get_category_link('strong');
// Show category description:
$lcp_display_output .= $this->get_category_description('p');
// Show the conditional title:
$lcp_display_output .= $this->get_conditional_title();
//Add 'starting' tag. Here, I'm using an unordered list (ul) as an example:
$lcp_display_output .= $this->open_outer_tag('select', 'lcp_catlist');
/* Posts Loop
*
* The code here will be executed for every post in the category. As
* you can see, the different options are being called from functions
* on the $this variable which is a CatListDisplayer.
*
* CatListDisplayer has a function for each field we want to show. So
* you'll see get_excerpt, get_thumbnail, etc. You can now pass an
* html tag as a parameter. This tag will sorround the info you want
* to display. You can also assign a specific CSS class to each field.
*
* IMPORTANT: Prior to v0.85 lines 65-67 were different. Make sure your
* template is up to date.
*/
global $post;
while ( $this->lcp_query->have_posts() ):
$this->lcp_query->the_post();
// Check if protected post should be displayed
if (!$this->check_show_protected($post)) continue;
//Start a List Item for each post:
$lcp_display_output .= $this->open_inner_tag($post, 'option');
//Show the title and link to the post:
$lcp_display_output .= $this->get_post_title($post);
// Show categories
$lcp_display_output .= $this->get_posts_cats($post);
// Show tags
$lcp_display_output .= $this->get_posts_tags($post);
//Show comments:
$lcp_display_output .= $this->get_comments($post);
//Show date:
$lcp_display_output .= $this->get_date($post);
//Show date modified:
$lcp_display_output .= $this->get_modified_date($post);
//Show author
$lcp_display_output .= $this->get_author($post);
// Show post ID
$lcp_display_output .= $this->get_display_id($post);
//Custom fields:
$lcp_display_output .= $this->get_custom_fields($post);
//Post Thumbnail
$lcp_display_output .= $this->get_thumbnail($post);
/**
* Post content - Example of how to use tag and class parameters:
* This will produce:<div class="lcp_content">The content</div>
*/
$lcp_display_output .= $this->get_content($post, 'div', 'lcp_content');
/**
* Post content - Example of how to use tag and class parameters:
* This will produce:<div class="lcp_excerpt">The content</div>
*/
$lcp_display_output .= $this->get_excerpt($post, 'div', 'lcp_excerpt');
// Get Posts "More" link:
$lcp_display_output .= $this->get_posts_morelink($post);
//Close li tag
$lcp_display_output .= $this->close_inner_tag();
endwhile;
// Show no posts text if there are no posts
$lcp_display_output .= $this->get_no_posts_text();
// Close the wrapper I opened at the beginning:
$lcp_display_output .= $this->close_outer_tag();
// If there's a "more link", show it:
$lcp_display_output .= $this->get_morelink();
// Get category posts count
$lcp_display_output .= $this->get_category_count();
//Pagination
$lcp_display_output .= $this->get_pagination();
$this->lcp_output = $lcp_display_output;
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Critical Error when editing menu I am having an issue debugging what appears to be a WP core issue.
I am observing the following behavior when attempting to edit menus, see below for context
I checked the error logs and the following error is logged when edit menu page is loaded
PHP Fatal error: Uncaught Error: Attempt to assign property "posts_page" on null in ../../../wp-admin/includes/nav-menu.php:406\nStack trace:\n#0 ../../../wp-admin/includes/template.php(1536): wp_nav_menu_item_post_type_meta_box(NULL, Array)\n#1 ../../../wp-admin/nav-menus.php(945): do_accordion_sections(Object(WP_Screen), 'side', NULL)\n#2 {main}\n thrown in ../../../wp-admin/includes/nav-menu.php on line 406, referer: https://stagehqtrucks.wpengine.com/wp-admin/
I've changed the theme to a copy of the standard 2021 WP theme, disabled all of the plugins and the error persists. So it doesn't seem to be from the theme or plugin.
I also ran a high-security scan via Wordfence for anything malicious and that came back clean.
The site is on WP Engine, running PHP 8.
Downgrading PHP to 7.4 solves the issue but we are trying to upgrade.
Having trouble pinning down the error and figuring what else to look at..
A: The posts_page variable is looking for a page set as the "blog" page in the reading settings. At some point this was unset or the blog page was removed, it is not clear, but simply making a blank page and setting it as the "blog" page under settings->reading resolved the issue.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I disable theme.json default styles on a custom block I am trying to make a custom block but the theme.json styles override my styles (e.g a underline). I have tried adding a classic class which removes default settings like so:
.classic a, a.classic{
text-decoration: none;
}
but the theme.json rules are more specific and override it:
.editor-styles-wrapper a:where(:not(.wp-element-button)) {
text-decoration: underline;
}
Is there a way to stop theme.json styles from styling my block without using !important or inline / id selector?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wrap post titles containing slashes on narrow viewports I have a post title consisting of two words with a slash between. It seems that the web considers this to be one word rather than two, and it doesn’t wrap when viewed on a phone. I would like for this title to wrap where the slash is. Is there a way to specify that a slash should be treated like a hyphen for word wrapping purposes?
A: I have not found a way to specify that a slash should be treated like a hyphen.
One potential workaround is to add the style overflow-wrap: break-word;. This will allow long words to break without affecting the breaking of other words. But it will just break at whatever character would cause overflow, it doesn’t prefer breaking at slash characters.
Breaking at specific characters, such as the slash character, can’t be done in CSS, you have to do it in HTML. If you have access to the HTML code (in a post body, for example) you can choose any of these solutions:
*
*<wbr> word break opportunity tag
*​ zero width space
*​ zero width space
But these don’t work for a post title in WordPress, because WordPress will filter out any code you enter into a post title. The way to solve this is to insert one or more zero-width-space characters directly into the title. One way to do this is to use Character Viewer (Mac) or Character Map (Windows), although of course they are a bit tricky to use when it comes to spaces because spaces are invisible. In the case of Character Viewer, when you search for arrow, lots of matches appear, but when you search for zero width space, it appears that no characters were found. But if you click where the blue square is in the second image below, you’ll discover that the character was found, it’s just invisible.
And you can see the result:
More details are available in this answer on Stack Overflow, including a snippet to demonstrate the differences between the various HTML solutions.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: change title of page dynamically i have a page that has an snippet code shortcut. in this snippet i call an Rest Api and show that information was response.
but now i want replace tag Title of this page with one rest api item.
i try make an variable global and cal it in add_filter but it seems add_filter was run before my snippets code.
can you help me to find some solution.
i use this code :
add_filter( 'pre_get_document_title', 'cyb_change_page_title' );
function cyb_change_page_title () {
global $title;
return $title;
}
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: add_action 'wp_after_insert_post' for custom post types I'm using Advanced Custom Fields and I would like a function to run when I either publish or update a custom post type. I've tried acf/save, add_action( 'wp_after_insert_post' and add_action( 'save_post_my_post_type' but the function doesn't fire when a custom post type is either published or updated. Is there a similar hook as add_action( 'wp_after_insert_post' I can use?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ask: Anonymization Data of live Wordpress site sorry, wondering for this scenario below there is a website which contains data about subscribers (email, name, etc) are there any way to encrypt or anonymize those data ?
I'm currently looking more about the details from original developer / admin of website:
*
*things i know is the data is put through paid membership pro plugin.
With using that paid membership pro do you think we can implement some methods to encrypt/secure/anonymize those data been input through paid membership pro?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Prevent URL Parameter Affecting other WP Query I have a loop the generates a list of custom post types as a menu:
$loop = new WP_Query(
array(
'post_type' => 'farm-shop',
'orderby' => 'menu_order',
)
);
The menu sometimes appears next to a woocommerce listing. When the user changes the order of the sorting for the woocommerce list, the url parameters affect my menu above.
For example if the user selects order by date (shop/?orderby=date&paged=1), the menu above gets ordered by date too.
Is there a way I can tell my menu to ignore the url parameters?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: wp_get_nav_menu_items array not getting 3rd level children I am using the below code for custom menu structure. The below code gives only 1st level child but not giving the 2nd child elements. Here is the code -
$array_menus = wp_get_nav_menu_items( 311 );
$menus = array();
foreach ($array_menus as $m) {
if (empty($m->menu_item_parent)) {
$menus[$m->ID] = array();
$menus[$m->ID]['ID'] = $m->ID;
$menus[$m->ID]['catID'] = $m->object_id;
$menus[$m->ID]['title'] = $m->title;
$menus[$m->ID]['url'] = $m->url;
$menus[$m->ID]['menu_item_parent'] = $m->menu_item_parent;
$menus[$m->ID]['children'] = array();
//$menus[$m->ID]['subchildren'] = array();
}
}
$submenu = array();
foreach ($array_menus as $m) {
if ($m->menu_item_parent) {
$submenu[$m->ID] = array();
$submenu[$m->ID]['ID'] = $m->ID;
$submenu[$m->ID]['catID'] = $m->object_id;
$submenu[$m->ID]['title'] = $m->title;
$submenu[$m->ID]['url'] = $m->url;
$submenu[$m->ID]['menu_item_parent'] = $m->menu_item_parent;
$submenu[$m->ID]['subchildren'] = array();
$menus[$m->menu_item_parent]['children'][$m->ID] = $submenu[$m->ID];
}
}
$subsubmenu = array();
foreach ($array_menus as $m) {
if ($m->menu_item_parent==$submenu[$m->menu_item_parent]['ID']) {
$subsubmenu[$m->ID] = array();
$subsubmenu[$m->ID]['ID'] = $m->ID;
$subsubmenu[$m->ID]['catID'] = $m->object_id;
$subsubmenu[$m->ID]['title'] = $m->title;
$subsubmenu[$m->ID]['url'] = $m->url;
$subsubmenu[$m->ID]['menu_item_parent'] = $m->menu_item_parent;
$submenu[$m->menu_item_parent]['subchildren'][$m->ID] = $subsubmenu[$m->ID];
}
}
print_r($menus);
Can anyone please help how can i get 2nd level menu element in the above code?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Upload multiple files via ajax from an HTML file input I'm trying to upload files from a multiple file upload HTML input via ajax on a WordPress site but I keep getting a 400 error and I'm not sure why. My code is based on this tutorial.
jQuery:
$(document).on('change','input[type="file"]',function(){
var fd = new FormData();
var files_data = $(this); // The <input type="file" /> field
// Loop through each data and create an array file[] containing our files data.
$.each($(files_data), function(i, obj) {
$.each(obj.files,function(j,file){
fd.append('files[' + j + ']', file);
})
});
fd.append('action', 'file_upload');
fd.append('nonce', $('#file_upload_nonce').val());
fd.append('application_id', $(this).closest('.application_question').attr('data-application-id'));
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: fd,
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
});
PHP:
function file_upload(){
// Check the nonce first
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'file_upload' ) ) {
echo 'Security validation failed.';
} else {
$application_id = $_POST['application_id'];
foreach ( $_FILES['files']['name'] as $f => $name ) {
move_uploaded_file( $_FILES["files"]["tmp_name"][$f], '/wp-content/supporting-evidence/' . $application_id . '/' . $_FILES["files"]["name"][$f] );
}
}
wp_die();
}
add_action('wp_ajax_file_upload','file_upload');
What am I doing wrong here?
A: It's because you're logged out and the code does not handle that
There is also a major security hole in the code, scroll down to see the details
HTTP 400 and a 0 is what admin-ajax.php returns when it cannot find a handler for your AJAX request.
Note that if you had used the modern REST API instead of the legacy admin-ajax.php API it would have told you this in plaintext human readable language and a 404 like this:
{"code":"rest_no_route","message":"No route was found matching the URL and request method.","data":{"status":404}}
It would also have responded with a 403 forbidden if you'd made the same mistake, which is much harder to make when using AJAX with a REST API endpoint
If we look at the tutorial we can see where it adds the AJAX handler action:
add_action('wp_ajax_cvf_upload_files', 'cvf_upload_files');
add_action('wp_ajax_nopriv_cvf_upload_files', 'cvf_upload_files'); // Allow front-end submission
But, if we look at the code in your question:
add_action('wp_ajax_file_upload','file_upload');
Your code has 1 action, the tutorial has 2. You're missing the wp_ajax_nopriv_ version.
Overrall, keep in mind this is an 8 year old tutorial from 2015, and you shouldn't follow just a single tutorial when researching things. The official WordPress developer docs explain this much better, and since that tutorial was written a new modern API for AJAX called the REST API was written.
Further Notes
*
*you never checked that move_uploaded_file worked or not, it returns a false value if it failed, you need to check for this or it will fail silently and you'll be scratching your head trying to figure out why files are missing
*it needs to create the folder!
*you should not assume the location of the upload folder, the tutorial you shared uses wp_upload_dir() instead of assuming /wp-content/uploads to do this
*What if $_POST['application_id'] contained something malicious? e.g. ../? or myapplicationID/and/this/is/a/subfolder?
*the AJAX happens every time the file input changes, which means if I accidentally pick the wrong file, it's instantly uploaded and I can't get it back! What if I picked something confidential by accident that was next to it and now we're both in trouble? Or if I select the same file 5 times, now there are 5 copies on your server. What if I accidentally select a 24GB blueray backup file?
*
*the tutorial also has a check for this, but your code does not
A Major Security Problem In The Code
*
*There is no validation on the files, I could use this to upload and run PHP files!!!!
*
*the tutorial you're following uses the wp_check_filetype function to do this
*I could use your form to submit PHP files that give me total control over your website then just visit example.com/wp-content/supporting-evidence/myapplicationID/hacksite.php, this is very dangerous!
*at a minimum check the file extensions, WordPress has functions for checking valid filetypes
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: get page_id in ajax to function in functions.php Im loading "read more"-content via ajax and json. This works global for all pages. But I need the extra-content only from the current page Im viewing. Now I want to pass the page_id into my function but cant get it work. I tried setting the ID by click on my readmore-link or getting the ID through my localize_script var.
Could somebody please help me?
functions.php
function get_extra_content() {
$content = array();
$args = array(
'post_type' => array('page'),
'p' => $post_id
);
$result = new WP_Query($args);
if ($result->have_posts()): while ($result->have_posts()) : $result->the_post();
...
endwhile; endif;
echo json_encode($content);
wp_die();
}
add_action('wp_ajax_nopriv_get_extra_content', 'get_extra_content');
add_action('wp_ajax_get_extra_content', 'get_extra_content');
ajax
$('.morebtn').stop().click(function() {
postID = $(this).data('postid');
if ($(this).hasClass('active')) {
emptyReadMore();
$(this).stop().toggleClass('active');
}
else {
showReadMore(postID);
$(this).stop().toggleClass('active');
}
});
function showReadMore(postID) {
$.ajax({
url: ajax_actions.ajaxurl,
dataType: 'json',
data: {
action: "get_extra_content",
post_id: postID //or ajax_actions.postid
},
beforeSend: function() {
...
},
complete: function(){
...
},
success: function(data) {
...
},
error: function (errorThrown) {
...
}
});
}
wp_localize_script
global $post;
wp_register_script('scripts', get_template_directory_uri() . '/assets/js/scripts.js','','',true);
wp_localize_script('scripts', 'ajax_actions', array('ajaxurl' => admin_url( 'admin-ajax.php' ), 'postid' => $post->ID));
wp_enqueue_script('scripts');
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In Full-Site-Editing, edits made to the code in a template part are not showing I trying to get my head around FSE and template parts. I was able to create a header in the Gutenberg editor and copy the code to header.html. However, when I edit the header.html code directly in my text editor, e.g., add a dashicon, it doesn't show in the header on the site or in the editor.
Is the only way to add to header.html in the editor and then copy the code? In essence, header.html is really only a back-up? I can go backwards? Edit the html and have it work?
What am I missing?
Brad
A: It's probably because you made edits in the site editor which created a template/template_part post in the database, and that's what's being used, not your original HTML.
Unlike PHP templates, the HTML files in a block theme are the starting points. Once a user makes changes/additions those changes are saved in the database and take precedence. You would need to export those changes back to HTML files and replace the ones in your theme with the new versions, or delete the posts in the site editor.
It's generally best to use the site editor to make your changes, not the raw HTML. Some blocks may start to fail block validation if you deviate too much, and user changes might cause data loss when your changes don't map to anything a block normally generates. Lots of custom HTML blocks also makes your theme unintuitive and difficult to work with.
From what I can tell this is the precedence order:
*
*DB user template for current active theme
*HTML template file in child theme
*HTML template file in parent theme
*PHP template in child theme
*PHP template in parent theme
Do confirm this though as I'm not 100%
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How To Add CSP frame ancestors in Wordpress Website? I'm trying to add Content Security Policy (CSP) frame ancestors in .htaccess file to prevent our website from getting iframed on other websites.
Following is the code:
<IfModule mod_headers.c>
Header set Content-Security-Policy "frame-ancestors 'self';"
</IfModule>
This requires mod_headers to be enabled.
But when we enable mod_headers, it gives us Internal Server Error.
Note: We have a plugin installed that uses mod_header in .htaccess.
Prevent other sites from showing my site via iframe
Note 2: I am using Apache2 Server
Note 3 (Very Important): When we remove the mod_headers added by the above plugin, the CSP header gets added and no error is encountered.
But we do not want to remove the plugin / mod_headers added by the plugin.
Following is the error reported in apache's error logs-
/var/www/html/.htaccess: SetEnvIfNoCaseHeader name regex could not be compiled.In .htaccess, this is the part where SetEnvIfNoCaseHeader is getting used -
# Force deflate for mangled headers
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X-]{4,13}$ HAVE_Accept-Encoding
RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
# Don't compress images and other uncompressible content
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png|rar|zip|exe|flv|mov|wma|mp3|avi|swf|mp?g|mp4|webm|webp|pdf)$ no-gzip dont-vary
</IfModule>
</IfModule>
Please Note:
Server version: Apache/2.4.41 (Ubuntu)
A:
SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X-]{4,13}$ HAVE_Accept-Encoding
The regex ^(Accept-EncodXng|X-cept-Encoding|X{15}|{15}|-{15})$ is invalid, hence the error you are getting. Specifically, the error is here:
^(Accept-EncodXng|X-cept-Encoding|X{15}|{15}|-{15})$
---------------------------------------^
{15} is a quantifier, but the preceding token | is not quantifiable, since this is itself a special meta character. There is something missing. But it's not clear what this should be just by looking at the regex. However, it's possible this rule is based on the findings of this PDF/slides from 2009 (regarding mangled Accept-Encoding headers) so would make the missing character a ~ (tilde) - but that list is far from exhaustive (and in most cases the Accept-Encoding header is stripped entirely, which this rule does not check for). For example:
^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$
Or you could just make the regex valid by removing that part of the alternation altogether. For example:
^(Accept-EncodXng|X-cept-Encoding|X{15}|-{15})$
Although this and the following RequestHeader directive are only to "fix a mangled" Accept-Encoding header, and in the majority of cases where this would apply, the Accept-Encoding header is stripped entirely (which this rule does not check for). It's debatable whether this is required with today's web.
Just by looking at this rule block it's not clear whether the second SetEnvIfNoCase directive is required or not. (Although I assume you are compressing the response with Apache?)
Needless to say, this error has little to do with mod_headers. It just so happens that this directive is inside an <IfModule mod_headers.c> container.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Display a block conditionally based on user input button I am looking to put 2 donation forms on a page using a shortcode (or block) and I want them displayed based on currency selected by user,So for instance a user comes onto the page he will see 2 buttons, One showing "currency A" and one showing "currency B".If the user selects "Currency A" I want block A displayed and if they choose "Currency B I want block B displayed.How can I achieve that? (I imagine through JS but is there a simple snippet that can achieve that for me?)
A: I think the most simple approach (if you're able to add some JS) is to use custom classes for your buttons and blocks that can be settled through advanced settings in block editor. Then a really basic JS snippet can do the trick.
Here's an example in vanilla JS with an IFFE that takes care of waiting for DOM to be loaded : https://codepen.io/liqueurdetoile/pen/dyjEYEP
Obviously class names have to be chosen wisely to avoid any trouble.
EDIT - You can also use any accordion block for Gutenberg to achieve a similar result. There's plenty available as plugins.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add custom text to product category page I am using Advanced Custom Fields and want to add a display a custom text below the product image on the Woo product category page.
I used this but nothing is showing:
add_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
function woocommerce_shop_loop_item_title() { ?>
<?php if(get_field(product_promo_loop')) { ?>
<div class="style"><?php the_field('product_promo_loop'); ?></div>
<?php
}}
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: getBlockVariations(…) is undefined in Widget and Template Part editors but not Post Editor I'm using this technique to hide various embed blocks:
wp.domReady( function() {
/*
* Hide Embed Variations
*/
wp.blocks.getBlockVariations('core/embed').forEach(function (embed) {
// loop through a bunch of embeds
});
});
The file with that script is registered and enqueued like this:
<?php
wp_register_script(
'block-editor-js',
plugins_url( 'js/block-editor.js', dirname(__FILE__) ),
array( 'wp-blocks', 'wp-dom-ready', 'wp-edit-post' )
);
wp_localize_script(
'block-editor-js',
'editorOptions',
[ /* some values */ ]
);
wp_enqueue_script( 'block-editor-js' );
This works as expected in the block editor!
It does not work in the block-based widget editor or the template part editor. In Firefox in both cases, I get the following error:
Uncaught TypeError: wp.blocks.getBlockVariations(...) is undefined
I am totally flummoxed as to what the issue is. My two guesses are that I need some additional dependencies on the pages that break or that domReady is too early and I need to hook onto somewhere later.
Any help will be greatly appreciated!
A: Here's why did you get an undefined
The function itself was defined, but the function call (wp.blocks.getBlockVariations( 'core/embed' )) returned an undefined because by the time that you called the function, the block/Gutenberg editor had not yet been initialized.
Hence, undefined was returned instead of an array of block variations, because core block types like Embed had not yet been registered — and if you had called wp.blocks.getBlockTypes(), you'd see that core/embed is not in the list.
How to ensure your code runs properly
WordPress uses wp_add_inline_script() to add an inline script which calls the function that initializes the editor, so you need to add the same dependency passed to wp_add_inline_script(), which is the 1st parameter, to your script's dependencies ( the 3rd parameter for wp_register_script() ):
*
*For the block-based post editor, the dependency is wp-edit-post which will load wp-includes/js/dist/edit-post.js that defines wp.editPost.initializeEditor() and is used to initialize the block-based post editor.
See source on GitHub: wp-admin/edit-form-blocks.php, line 303 and line 290
*For the block-based widgets editor, the dependency is wp-edit-widgets which will load wp-includes/js/dist/edit-widgets.js that defines wp.editWidgets.initialize() and is used to initialize the block-based widgets editor.
See source on GitHub: wp-admin/widgets-form-blocks.php, lines 38-46
*For the Site Editor, the dependency is wp-edit-site which will load wp-includes/js/dist/edit-site.js that defines wp.editSite.initializeEditor() and is used to initialize the Site Editor.
See source on GitHub: wp-admin/site-editor.php, lines 120-128
So, just add either wp-edit-post, wp-edit-widgets or wp-edit-site to your script's dependencies, depending on the current admin page, or the editor type (post/widgets/site).
That way, the editor initialization function would already be defined and called when you call wp.blocks.getBlockVariations() and thus, you'd get the proper result.
Working Example
$deps = array( 'wp-blocks', 'wp-dom-ready' );
global $pagenow;
// If we're on the Widgets admin page, add wp-edit-widgets to the dependencies.
if ( 'widgets.php' === $pagenow ) {
$deps[] = 'wp-edit-widgets';
// If we're on the Site Editor admin page, add wp-edit-site to the dependencies.
} elseif ( 'site-editor.php' === $pagenow ) {
$deps[] = 'wp-edit-site';
// If we're on the post/Page/CPT editing screen (e.g. at wp-admin/post.php), add
// wp-edit-post to the dependencies.
} else {
$deps[] = 'wp-edit-post';
}
wp_register_script(
'block-editor-js',
plugins_url( 'js/block-editor.js', dirname(__FILE__) ),
$deps
);
Notes
*
*I used the enqueue_block_editor_assets action/hook to run the above code.
*The minified version of the JS files mentioned above, where the file name ends with .min.js, will be loaded instead when script debugging is not enabled.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Shortcode Displays 2 times Created the shortcode but it displays twice whenever I use it.
Here is the code:
function blog_cta() {
$blog_cta = '';
$blog_cta .= '<div class="article-cta-box">';
$cta_box_section_heading = get_field('cta_box_section_heading', $post->ID);
$cta_button = get_field('cta_button', $post->ID);
if ( $cta_box_section_heading !== '' ) {
$blog_cta .= '<div class="article-cta-box--col-one"><img src="' . get_template_directory_uri() . '/assets/images/article-cta-box-art.svg" alt="" role="presentation"></div><div class="article-cta-box--col-two">
<img src="' . get_template_directory_uri() . '/assets/images/gust-launch-small-logo.svg" alt="" role="presentation">
<div class="cta-details-wrapper"><h3>' . $cta_box_section_heading . '</h3>';
}
if ( $cta_button !== '' ) {
$blog_cta .= '<div class="btn-wrapper">
<a href="' . $cta_button['url'] . '" target="' . $cta_button['target'] . '" class="main-btn">' . $cta_button['title'] . '</a></div></div></div>';
}
$blog_cta .= '</div>';
return $blog_cta;
}
add_shortcode('location_blog_cta', 'blog_cta');
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get related posts matching most of the provided tags using WP_Query I need help in getting related posts using multiple tags.
I have posts with the tags poetry, motivational, attitude, rules, lines, sigma and inspirations.
I want related posts matching most of these tags using WP_Query.
Note: each post doesn't have all of these tags.
A: There is no direct way of getting posts matching most of these tags using WP_Query.
The usual documented methods:
If you want posts matching any of these tags, you may use:
$args = array(
'post_type' => 'post',
'tag_slug__in' => array( 'poetry', 'motivational', 'attitude', 'rules', 'lines', 'sigma', 'inspirations' )
);
$query = new WP_Query( $args );
Also, if you want posts matching all of these tags, you may use:
$args = array(
'post_type' => 'post',
'tag_slug__and' => array( 'poetry', 'motivational', 'attitude', 'rules', 'lines', 'sigma', 'inspirations' )
);
$query = new WP_Query( $args );
Getting posts with most of these tags:
To achieve what you want, you'll have to either use a custom SQL query or some advanced customizations to the WP_Query generated SQL query using hooks.
For example, you may use the posts_clauses hook combined with pre_get_posts hook to alter the SQL generated by WP_Query.
To get posts with most of these tags, you'll need to include count( wp_term_relationships.object_id) in SELECT portion of the generated SQL query, and then sort the query result by that count in descending order.
The following is the code of a complete plugin that implements this logic:
<?php
/**
* Plugin Name: @fayaz.dev Related posts by most tags
* Description: Show related posts by of the provided tags
* Author: Fayaz Ahmed
* Version: 1.0.0
* Author URI: https://fayaz.dev/
**/
namespace Fayaz\dev;
/**
* Any WP_Query where 'order_by_most_tags' is set as an argument,
* will be altered by this function, so that the query result is
* ordered by the number of matching tags in descending order.
* However, if no matching tag is provided, then that query will not
* be altered by this.
*/
function filter_posts_by_most_tags( $query ) {
if( isset( $query->query['order_by_most_tags'] )
&& isset( $query->query_vars['tag_slug__in'] ) && ! empty( $query->query_vars['tag_slug__in'] ) ) {
add_filter( 'posts_clauses', '\Fayaz\dev\add_select_count_tags', 10, 2 );
}
}
add_action( 'pre_get_posts', '\Fayaz\dev\filter_posts_by_most_tags' );
function add_select_count_tags( $clauses, $wp_query ) {
global $wpdb;
// database query modification needed for ordering based on most tags
$clauses['fields'] = $clauses['fields'] . ', count( ' . $wpdb->term_relationships . '.object_id ) as number_of_tags';
$clauses['orderby'] = 'number_of_tags DESC, ' . $clauses['orderby'];
// we only need this once, so it's better to remove the filter after use
remove_filter( 'posts_clauses', '\Fayaz\dev\add_select_count_tags', 10, 2 );
return $clauses;
}
Sample Plugin Usage:
The above plugin implements a custom WP_Query argument named order_by_most_tags. When it's set, the plugin will alter the result to get posts with most of the provided tags.
One you activate the plugin, use the code as shown below in your currently active theme's template files (e.g. single.php):
$args = array(
'post_type' => 'post',
'tag_slug__in' => array( 'poetry', 'motivational', 'attitude', 'rules', 'lines', 'sigma', 'inspirations' ),
'order_by_most_tags' => 1,
// other order by (in case there are multiple matches with most tags)
'orderby' => array( 'comment_count' => 'DESC', 'date' => 'ASC' )
);
$post_ID = get_the_ID();
if( $post_ID ) {
// exclude current post
$args['post__not_in'] = array( $post_ID );
}
echo '<h2>Related Posts</h2>';
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
echo '<ul>';
while ( $query->have_posts() ) {
$query->the_post();
echo '<li>';
?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
<?php
echo '</li>';
}
echo '</ul';
}
else {
echo '<h2>Nothing is found</h2>';
}
// Restore original Post Data, needed if this was run in a loop
wp_reset_postdata();
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Broken links on terms list page I've registered a custom taxonomy for a custom post type. Every term on the admin term list page has a link to the list of posts filtered by that term.
This link should look like this:
for a custom post type:
.../edit.php?taxonomy-name=taxonomy-term-name&post_type=post-type-name
for posts:
.../edit.php?taxonomy-name=taxonomy-term-name
However, for my taxonomy the links do not have the post_type argument, resulting in links like .../edit.php?taxonomy-name=taxonomy-term-name which makes the links lead to regular posts list filtered by a term of a taxonomy they don't have. I can't figure out why this is.
My code:
//register a post type in a plugin
add_action( 'init', 'register_post_type_tdlrm_store_item', 10 );
function register_post_type_tdlrm_store_item() {
$labels = array(
//omitted
);
$args = array(
'label' => __( 'Item', 'text_domain' ),
'description' => __( 'Store items', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'thumbnail', 'comments', 'revisions' ),
'taxonomies' => array( 'store-category' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => false,
'menu_position' => 5,
'menu_icon' => 'dashicons-cart',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
'rewrite' => array('slug' => 'product')
);
$args = apply_filters('tdlrm_filter: tdlrm_store_item: alter register_post_type arguments', $args);
register_post_type( 'tdlrm_store_item', $args );
}
//register taxonomy in another plugin
add_action( 'init', 'register_ingredients_taxonomy', 99);
function register_ingredients_taxonomy(){
$labels = array(
//omitted
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => false,
'rewrite' => array( 'slug' => 'ingredient' ),
);
register_taxonomy( 'tdlrm_ingredients', array( 'tdlrm_store_item' ), $args );
}
//I tried to fix the situation
add_filter('tdlrm_filter: tdlrm_store_item: alter register_post_type arguments', 'alter_post_type_arguments');
function alter_post_type_arguments($arguments){
if(!in_array('tdlrm_ingredients', $arguments['taxonomies'])){
$arguments['taxonomies'][] = 'tdlrm_ingredients';
}
return $arguments;
}
I don't understand why this gives me wrong links.
Also, I have re-saved permalinks just in case, to no effect.
Update
I get to the term list page via a custom link in a sub-menu. The link have been added like this:
add_action('admin_menu', 'add_menu_link', 50);
function add_menu_link(){
add_submenu_page(
'TDLRM',
'Ingredients',
'Ingredients',
'edit_posts',
'edit-tags.php?taxonomy=tdlrm_ingredients',
''
);
}
A:
However, for my taxonomy the links do not have the post_type argument
Yes, and it's because that argument does not exist in your submenu slug or relative URL (the 5th parameter for add_submenu_page()), therefore WordPress would not know that you're targeting your post type, and WordPress also would not add that argument to the links for filtering posts by your taxonomy at wp-admin/edit.php.
Remember that taxonomies can be attached to two or more post types, hence you should always include the post_type argument in your submenu link, even if your taxonomy will only ever going to have one post type. Because when that argument is missing or not specified, WordPress will not default to using the only post type attached to a taxonomy having just one post type attached.
So make sure to include that argument, just like WordPress does it when show_in_menu is not specified or is set to true:
add_submenu_page(
'TDLRM',
'Ingredients',
'Ingredients',
'edit_posts',
'edit-tags.php?taxonomy=tdlrm_ingredients&post_type=tdlrm_store_item',
''
);
Additional Notes
*
*As I commented, you could actually set show_in_menu to the slug of a top-level menu page added using add_menu_page(), but you would want to use 9 or lower as the action's priority as in add_action( 'admin_menu', 'your_function', 9 ). More details here (see the 1st note)
And if that's not preferred (e.g. because you want another submenu item as the first one, but you need to use 10 or more as the action's priority), then just use 'show_in_menu' => false and manually call add_submenu_page() to add your post type as a submenu of your admin menu.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it within WordPress guidelines to update another plugin's database fields from my own plugin? Is it within the WordPress guidelines and acceptable practices to modify the database fields of another plugin, specifically the meta description fields, from my own plugin?
I would like to check if either Yoast SEO or All in One SEO is enabled and generate a meta description, updating the corresponding fields in the database.
I can technically do this but my concern is whether or not this is an acceptable practice and dont violates WordPress policy.
A: WordPress guidelines doesn’t restrict doing this. In fact, modifying database directly is no different from doing update_post_meta() or update_option() which are used widely everywhere.
However, modifying data of other plugins need to be done carefully because the data might be referred somewhere else.
I’d recommend using the plugins’ hooks to get/change the data instead of modifying it directly.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Elementor article preview picture have different size i'm working on a site with post, and the picture take the space they want. It show them good on editor but once on the live site they ignore the size i put. Any idea on how to fix? I'v try plugins to resize etc.. but nothing work. Thanks!
(I put random image as exemple)
How it look on editor and should look on live website:
How it look in live:
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why doesn't "wp db cli" enable tab completion? I would like to use tab completion when using the MySQL REPL accessed by running wp db cli. However it doesn't seem to work, even though my ~/.my.cnf file contains this content:
[mysql]
auto-rehash
If I use the mysql command directly, tab completion does work.
Running wp db cli --defaults doesn't seem to fix the problem.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I want to update shipping charge $0 for all Woocommeerce Subscription auto-renewal orders Do we have any woocommerce subscription auto-renewal hooks where we can update the shipping charges? In my case for all the auto-renewal I want to update the shipping charge to $0.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wordpress core files - PHP Warning: file_exists(): open_basedir restriction in effect Our live site went down this afternoon with the open_basedir issue. The odd thing being that it doesn't relate to media uploads etc. but to one of the core files. The wp-admin/setup-config.php file more specifically.
Here is the full error I'm getting:
"PHP message: PHP Warning: file_exists(): open_basedir restriction in effect.
File(/www/{mydomain}/wp-config-sample.php) is not within the allowed path(s):
/www/{mydomain}/public:/www/{mydomain}/mysqleditor:/www/{mydomain}/web:/www/{mydomain}/deploy:/www/{mydomain}/deployment:/www/{mydomain}/deployments:/usr/share:/tmp) in /www/{mydomain}/public/wp-admin/setup-config.php on line 46" while reading response header from upstream
Would greatly appreciate any help as this is detrimental to our business and we would be forced to start giving refunds if not resolved soon.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to use a post name in a custom post slug? So I have custom post type called Lessons and I am using something like this for the slug
register_post_type( 'Lessons',
// CPT Options
array(
'labels' => array(
'name' => __( 'Lessons' ),
'singular_name' => __( 'Lesson' )
),
'public' => true,
'has_archive' => false,
'rewrite' => array('slug' => '%postname%-lessons'),
'show_in_rest' => true,
'supports' => array( 'title', 'custom-fields','thumbnail' ),
)
);
But it's not working, any idea if this is even possible?
A: Rewrite is a global base for all posts under the custom post type. For example, this is the default CPT rewrite structure:
example.com/lesson/%postname%
In your code example, it's implying you are trying to do:
example.com/%postname%-lesson/%postname%
Two issues with this idea. The first issue, assuming this functionality worked, is that your CPT urls would all be inconsistent with each other. Because the rewrite slug is global across all your custom posts, every custom post would have their own uniquely different rewrite rule which would be a nightmare to keep track of. The second issue is more relative to the fact that this idea does not work. The rewrite is literal to '%postname%' meaning your post urls would all try to be accessible at exactly /%postname%-lesson/. The % character will break the url entirely and make the post inaccessible.
If you are wanting to remove the CPT slug from in front of the post name, update 'rewrite' to array('with_front' => false),
Then you could implementing a solution such as https://stackoverflow.com/a/4518634. Add in a check against the current post_type, and append any string you want (such as -lesson). This could allow you to achieve a permalink structure such as:
example.com/%postname%-lesson
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Get category of post inside save_post hook I don't have much experience with hooks in WordPress so i have found a problem who don't look too difficult, but i can't find the answer.
In my project i have a metabox who will get the content after i make a category check inside my save_post hook.
But now i can't get the category selected and i don't know how can i know that info.
I'm using get_the_category($post_id) inside my hook, but this don't return my category.
My function is this below (and i got this from other question here):
function updatePost( $post_id, $post, $update ) {
// Stop anything from happening if revision
if ( wp_is_post_revision( $post_id ) ) {
return;
}
// unhook this function so it doesn't loop infinitely
remove_action( 'save_post', 'updatePost' );
// get post type
$post_type = get_post_type( $post_id );
// run codes based on post status
$post_status = get_post_status();
if ( $post_status != 'draft' ) {
if ( isset( $_POST['img-destacada'] ) ) {
get_the_category($post_id);
// here i will put some logic to set the $img value based on my category
$img = '';
update_post_meta($post_id, "img-destacada", $img);
}
}
// re-hook this function
add_action( 'save_post', 'updatePost', 100, 3 );
}
How can i get the category info to then set the $img value?
A: Your code calls get_the_category() but it doesn't use the value returned.
// ...
if ( isset( $_POST['img-destacada'] ) ) {
$categories = get_the_category($post_id);
$img = '';
// $categories should contain either an array of WP_Term objects,
// or an empty array.
if ( ! empty( $categories ) ) {
// Here I've used the slug of the first item in the array to set the $img.
// You may have other logic you want to use.
$img = $categories[0]->slug . '.jpg';
}
if ( ! empty( $img ) ) {
// Checks to make sure there's an $img set.
update_post_meta($post_id, "img-destacada", $img);
}
}
// ...
References
*
*get_the_category()
*WP_Term
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Reinitiate Gutenburg's blocks using javascript I'm developing a WordPress plugin that manipulates some Gutenberg blocks using javascript.
For better understanding, create a table in a post and run the code below in the console:
let tableHtml = document.querySelector(".wp-block-table").innerHTML;
document.querySelector(".wp-block-table").innerHTML = tableHtml;
I'm replacing the innerHTML of a block, and then if I try to change the table caption or delete the table, it won't work.
and I think it's because the table is changed and the eventListeners are all gone so I need to initialize them again, but I don't know how.
I think I found the function responsible for that, it's table_init located on wp-includes/js/dist/block-library.js but I don't know how to use it.
Any ideas?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trying to add taxonomy terms to search results page I have added a custom taxonomy as "Tempo" to denote whether the songs people are searching for are Up Tempo, Mid Tempo or Slow Tempo. The search filters them properly, but I am unable to get the taxonomy to display on the search results page properly without a Warning popping up. This is the code I am using so far on the search.php template-part (pls keep in mind I am not great at PHP and still learning) which is a mix of the theme developers search.php code and some other snippets I found while digging around to accomplish this task.
<div class="search-page-content">
<?php if ( have_posts() ) : ?>
<?php
while ( have_posts() ) :
// Get the taxonomy terms
$_terms = get_terms( array('tempo') );
foreach ($_terms as $term) :
$term_slug = $term->slug;
$term_link = get_term_link( $term );
$_posts = new WP_Query( array(
'tax_query' => array(
array(
'taxonomy' => 'tempo',
'field' => 'slug',
'terms' => $term_slug,
),
),
));
// Show the post results
the_post();
printf( '<h2><a="%s">%s</a></h2>', esc_url( get_permalink() ), esc_html( get_the_title() ) );
echo '<div class="search-meta-section">';
echo '<div class="search-tempo">';
echo '<a href="' . esc_url( $term_link ) . '">' . $term->name . '</a></ul>';
echo '</div>';
echo '<div class="search-category">'; the_category(); echo '</div>';
echo '</div>';
the_content();
wp_reset_postdata();
endforeach;
endwhile;
?>
<?php else : ?>
<p><?php esc_html_e( 'It seems we can\'t find what you\'re looking for.', 'hello-elementor' ); ?></p>
<?php endif; ?>
</div>
The Warning I am getting on the page is:
Warning: Undefined array key 5 in /homepages/31/d589186062/htdocs/coveracapellas/wp-includes/class-wp-query.php on line 3571
To be clear, the taxonomy terms ARE showing where I want them, and are clickable links to browse more items tagged with that taxonomy, but the Warning is what is throwing me for a loop.
A: I'm having some trouble understanding your code. It looks like you're:
*
*Looping over every search result.
*For each result, getting all tempo terms.
*For each tempo, querying all posts that belong to that term.
*Doing nothing with the queried posts.
This is all extremely inefficient and doesn't do anything like what you say you're trying to do.
If you want to display the list of tempos assigned to a search result in search.php you just need to use the_terms(). The result should look like this:
<div class="search-page-content">
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<h2>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h2>
<div class="search-meta-section">
<div class="search-tempo">
<?php the_terms( get_the_ID(), 'tempo' ); ?>
</div>
<div class="search-category">
<?php the_category(); ?>
</div>
</div>
<?php the_content(); ?>
<?php endwhile; ?>
<?php else : ?>
<p>
<?php esc_html_e( 'It seems we can\'t find what you\'re looking for.', 'hello-elementor' ); ?>
</p>
<?php endif; ?>
</div>
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: REST API error in block editor for custom templates I'm working on a plugin that adds custom templates to WordPress for use with the active theme. The template files are located in a plugin directory and are being passed into WordPress with the theme_templates hook.
What's stumping me is one small variation in an if statement results in the REST API returning an error when firing WP_REST_Posts_Controller::check_template(). The error is only present in the block editor as the classic editor bypasses the REST API check.
This is my function.
public function add_custom_templates($templates)
{
global $post_type;
/**
* Collect an array of templates files
*/
$templates = $this->template_files();
foreach ($templates as $template) {
/**
* Get header info from template file to parse template name and post type(s)
*/
$data = get_file_data( MY_TEMPLATES_PATH . $template, array(
'name' => 'Template Name',
'post_type' => 'Template Post Type'
));
// remove spaces if present
$trimmed = str_replace(' ', '', $data['post_type']);
//convert template data post type string to array
$post_types = explode(',', $trimmed);
// THIS WORKS <---
if (!empty($data['name']) && !empty($data['post_type'])) {
$custom_templates[$template] = $data['name'];
}
// THIS DOES NOT WORK <---
// if (!empty($data['name']) && !empty($data['post_type']) && in_array($post_type, $post_types)){
// $custom_templates[$template] = $data['name'];
// }
}
// manual override
$custom_templates['example.php'] = 'fake template';
return $custom_templates;
}
}
Let's assume $templates = array('one.php', two.php, three.php')
one.php has the following comment block below the opening tag
/*
* Template Name: Template One
* Template Post Type: post, page
*/
two.php has the following comment block below the opening tag
/*
* Template Name: Template Two
* Template Post Type: post, product
*/
three.php has the following comment block below the opening tag
/*
* Template Name: Template Three
* Template Post Type: page, product
*/
This working if statement returns all templates and allows for saving/updating inside the block editor without errors from the REST API
if (!empty($data['name']) && !empty($data['post_type'])) {
$custom_templates[$template] = $data['name'];
}
$custom_templates returns the following array: array(4) { ["one.php"]=> string(12) "Template One" ["two.php"]=> string(12) "Template Two" ["three.php"]=> string(14) "Template Three" ["example.php"]=> string(13) "fake template" }
However, that statement results in all 3 templates being accessible no matter the post type. I'm wanting to only include a template if the $data['post_type'] matches the global $post_type for the given post.
This if statement is supposed to limit it as per my intent.
if (!empty($data['name']) && !empty($data['post_type']) && in_array($post_type, $post_types)){
$custom_templates[$template] = $data['name'];
}
When running just the second if statement on a "page", $custom_templates returns the following array:array(3) { ["one.php"]=> string(12) "Template One" ["three.php"]=> string(14) "Template Three" ["example.php"]=> string(13) "fake template" }
*No matter which if statement is used, the manual override I added as a temporary sanity check is able to be selected and saved despite the lack of an actual file existing.
When running the if statement with in_array($post_type, $post_types) it correctly returns the templates I'm wanting to return, but any attempt to select and save that template inside the block editor results in the REST API kicking back the error "Updating failed. Invalid parameter(s): template".
Any help would be greatly appreciated as I'm stumped why the REST API is blocking the request *only when adding the extra check to my if statement.
A: It appears that the issue lies with the in_array function that is checking if the current post type matches the post types specified in the template header information. The problem seems to be that the REST API is validating the parameters, including the template parameter, before passing it to the WordPress API to update the post.
It's possible that the REST API is only allowing certain values for the template parameter and the values generated by the in_array function are not accepted. You can try to debug this by logging the values of $post_type and $post_types before and after the in_array function, as well as the $custom_templates array.
Another possible solution is to modify the REST API check_template method to accept the values generated by the in_array function. This would involve creating a custom REST API controller for the posts endpoint and including the check for the custom templates in the check_template method.
Lastly, you could also try using the WP_Query class instead of the REST API to retrieve and update the templates, as it is not as strict in terms of parameter validation.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting 400 Error in wordpress website When I go to my blog page and click on one of the topics from the table of contents. Note the table of contents is made by using a plug in that takes all the element and make the toc.
https://www.scrapingdog.com/blog/csharp-html-parser/
Now after that if I click on back button on browser, it shows 400 error which vanishes if I reload.
This problem only exists if I keep my permalinks option to "Postname". Once I change it to "Month and name" it works completely fine.
What should I do keep using post name permalink and the page also keep on working.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need help to be able to searching by tag and title Hello I am trying to get my search bar to search by titles and tags. I have a function working to search by titles but I cant seem to figure out how to search by tags. I have added the code below to my function.php I got this from https://wordpress.org/support/topic/search-within-results-tags-date-archive/
function search_archive_title() {
$type = '';
$var = '';
if (is_tag()){
$var = single_tag_title( '', false );
$action = 'tag/'.$var.'/';
}
}
echo '<form role="search" method="get" class="search-form" action="/'.$action.'">';
echo '<input type="text" name="s" value="" />';
echo '<button>Search</button>';
echo '</form>';
add_filter( 'posts_search', 'search_archive_title', 11, 2 );
I would very much appreciate some help Ive been trying a lot of things. I was trying with wp-query before but that wasn't working so I figured I would try this but if you have a better idea please let me know.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I want to Display custom woocomerce meta box in orders list I run a WooCommerce store and work with lots of delivery companies. To keep things organized, I added a custom post type where I can add new delivery companies. The meta box in the order details shows me the companies I created. Everything's good, but I can't seem to get the delivery company info to show up in a new column in the orders list.
here is the code used to create the custom meta box.
added meta box with a drop-down list to choose in order details which company this order
add_action( 'add_meta_boxes', 'add_delivery_company_to_order' );
function add_delivery_company_to_order() {
add_meta_box(
'delivery_company_to_order',
'Delivery Company',
'display_delivery_company_to_order',
'shop_order',
'side',
'default'
);
}
function display_delivery_company_to_order( $post ) {
$delivery_companies = get_posts( array(
'post_type' => 'delivery_company',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
) );
$selected_delivery_company = get_post_meta( $post->ID, 'delivery_company', true );
echo '<select id="delivery_company" name="delivery_company">';
echo '<option value="">' . __( 'Select a delivery company', 'woocommerce' ) . '</option>';
foreach ( $delivery_companies as $delivery_company ) {
$selected = selected( $selected_delivery_company, $delivery_company->ID, false );
echo '<option value="' . $delivery_company->ID . '" ' . $selected . '>' . $delivery_company->post_title . '</option>';
}
echo '</select>';
}
add_action( 'save_post', 'save_delivery_company_to_order' );
function save_delivery_company_to_order( $post_id ) {
if ( array_key_exists( 'delivery_company', $_POST ) ) {
update_post_meta(
$post_id,
'delivery_company',
$_POST['delivery_company']
);
}
}
here is the code used to create a new column to show the value
add_filter( 'manage_shop_order_posts_columns', 'add_delivery_company_column' );
function add_delivery_company_column( $columns ) {
$new_columns = array();
foreach ( $columns as $column_name => $column_info ) {
$new_columns[ $column_name ] = $column_info;
if ( 'order_total' === $column_name ) {
$new_columns['delivery_company'] = __( 'Delivery Company', 'woocommerce' );
}
}
return $new_columns;
}
add_action( 'manage_shop_order_posts_custom_column', 'display_delivery_company_in_order_list', 2 );
function display_delivery_company_in_order_list( $column ) {
global $post;
if ( 'delivery_company' === $column ) {
$delivery_company_id = get_post_meta( $post->ID, 'delivery_company', true );
if ( $delivery_company_id ) {
$delivery_company = get_post( $delivery_company_id );
echo $delivery_company->post_title;
} else {
echo '-';
}
}
}
Any ideas? thanks and sorry for my English
A: Solved it here is the answer
add_action( 'manage_shop_order_posts_custom_column', 'delivery_company_order_column_content', 10, 2 );
function delivery_company_order_column_content( $column, $post_id ) {
if ( $column === 'delivery_company_order' ) {
$order = wc_get_order( $post_id );
$delivery_company = get_post_meta( $order->get_id(), 'delivery_company', true );
$delivery_company_name = get_the_title( $delivery_company );
echo $delivery_company_name;
}
}
add_filter('manage_edit-shop_order_columns', 'delivery_company_order_column');
function delivery_company_order_column($columns)
{
$columns['delivery_company_order'] = 'Delivery Company';
return $columns;
}
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In Full Site Editing, how do I get the templates I created to appear in the site editor when populating a new page? I have created a Page template in the Appearance > Editor after creating a Header template part. In this Page template, I set up columns, image placeholders, text and headline placeholders, page title, etc. It was easy to create and looked fine.
I was also editing theme.json all along the way. I never used the Global Settings capability in the actual editor, but did tweak spacing using the Dimension tools, etc.
The Issue:
The content I created on a new page appears with the new template on the client side as I expected, but it does not appear in the site editor when editing the page.
I was under the impression that full-site-editing meant I could populate, style, and edit a page right in a "shell" of the Page template I created, 100% wysiwyg. Instead, all I see is raw text and images—no columns, header, etc., and nothing from the template. Note: the fonts and sizes set in theme.json are showing up fine.
So, is what I'm asking possible or am I not understanding FSE and templates?
A: When creating a page template in Appearance > Editor you can add a Post Content block. This is where the page content goes. Everything else is part of the template and applies to all Pages that use the template.
When you go to Pages > All Pages and select a page to edit, or use Edit Page in the admin bar, it will open the block editor for editing the page's content. From here you are only editing the contents of the Post Content block for that page.
Editing the template is the equivalent of editing page.php for classic themes, and the Post Content block is the equivalent of the_content() as used by classic themes.
However, while editing a page, if you edit the template by clicking Page > Summary > Template > Edit template it will open a view where you can edit the page template and the page content simultaneously. This will allow you to see the page content in the page template. It's important to note that any changes you make outside of the Post Content block will be saved to the template, meaning that they will apply to all pages. Changes made inside the Post Content block will be saved for the current page. If you make changes to both you will be asked which changes you'd like to save when you press Update.
If you want to create a set of blocks that acts as a starting point for the Post Content of a page then the feature you're looking for is Block Templates.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Properly sanitize an input field "Name " In my plugin I want administrators to be able to set the from name and email address in a single form field.
I anticipate the field content to be Name <[email protected]> However both sanitize_text_field() and sanitize_email() do their jobs and remove critical parts of the data.
Is there better way to do it rather than wp_kses()?
A: You could do something like this:
$input = 'Name <[email protected]>';
// Break the input into parts
preg_match( '/([^<]+)<([^>]+)>/i', $input, $matches, PREG_UNMATCHED_AS_NULL );
// Clean the name
$name = sanitize_text_field( $matches[ 1 ] );
// Clean the email
$email = sanitize_email( $matches[ 2 ] );
// Bail early if the values are invalid.
if ( !$name || !$email || !is_email( $email ) ) {
die( 'Invalid input' );
}
// Success!
$cleaned_input = "{$name} <{$email}>";
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Automatically added -2 in permalink after set number as permalink My website's permalink structure is /%postname%/ and I want to create permalink with number, for example for every new post I will create 1, 2, 3, etc. permalink for newer posts. But right now when I create permalink with 1, 2 or 3 then system automatically add -2 after number, and it becomes 1-2, 2-2, 3-2.
WordPress is installed in subdirectory on Nginx server and working fine.
What should I need to change?
[Edit Feb 13 UTC] More Details
*
*I started a forum and I didn't want to use a long permalink structure — by default, with the /%postname%/ structure, WordPress uses title as permalink and if user posted a post (a forum topic) with long title, then there will be long permalink which I don't want.
*So I'd like to have a short permalink like https://example.com/123 (i.e. <site URL>/<number>) and I think setting ID, or using the /%post_id%/ structure, is good approach. But, how we can set it continuous (1, 2, 3 etc. for newer post)? Right now when I published 3 posts, the permalink became /1/, /3/, /8/, and I don't know where is other ID number inserted because didn't add tag, cat or anything in between.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Redirect old homepage to the new one within the same site I am wondering how can I redirect the old homepage
https://blog.example.com/ to the new one https://www.example.com/ratgeber/
I have tried to redirect it via a WordPress Plugin, but when I insert the origin URL and the target URL I am getting the error message "ERR_TOO_MANY_REDIRECTS" .. for a better understanding of the issue you can take a look at the extract from a status-code-checker. I do not know how to solve this loop.
Could please someone tell me the correct syntax to put in the .htaccess? Hereby you can see all the directives included at the present moment in this file. The very first two lines of code are unfortunately not working as desired.
RewriteCond %{HTTP_HOST} ^blog\.(terminsvertreter\.com) [NC]
RewriteRule ^ https://www.%1/ratgeber%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://www.terminsvertreter.com/%{REQUEST_URI} [R,L]
# BEGIN WordPress
# Die Anweisungen (Zeilen) zwischen `BEGIN WordPress` und `END WordPress` sind
# dynamisch generiert und sollten nur über WordPress-Filter geändert werden.
# Alle Änderungen an den Anweisungen zwischen diesen Markierungen werden überschrieben.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
A: Ideally, the blog subdomain would point to a different filesystem location (its own document root), then you could use a simple Redirect directive in its own .htaccess file in the root of the subdomain. For example:
Redirect 301 / https://www.example.com/ratgeber/
The Redirect directive is prefix-matching and everything after the match is copied onto the end of the target, so https://blog.example.com/anything is redirected to https://www.example.com/ratgeber/anything.
However, if both hostnames point to the same place (as would seem to be the case) then you will need to use mod_rewrite at the very top of the root .htaccess file. For example:
RewriteCond %{HTTP_HOST} ^blog\.(example\.com) [NC]
RewriteRule ^ https://www.%1/ratgeber%{REQUEST_URI} [R=301,L]
This specifically checks for the blog.example.com hostname in the preceding condition. The %1 backreference simply saves repetition having captured the domain name in the preceding condition.
The REQUEST_URI server variable already contains the slash prefix.
Always test first with a 302 (temporary) redirect to avoid potential caching issues. You should clear your browser cache before testing.
If you aren't serving multiple domains (that could also have a blog subdomain) then you can make the rule entirely generic (to avoid hardcoding the domain name), to redirect from the blog subdomain to www (plus subdirectory). For example:
RewriteCond %{HTTP_HOST} ^blog\.(.+?)\.?$ [NC]
:
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Background Tasks in a WP Cronjob? I have specific tasks which I want to perform every 15s in the background to update some cache / transients. I already use an external Cronjob service that triggers the Cron runs in WP - but unfortunately it can only trigger the cronjobs every 1min.
My simple idea to solve it was
I could simply do a for-loop which does it:
for($i = 0; $i < 5; $i++) {
update_my_cache();
sleep(15);
}
Big caveat: This would obviously block other PHP tasks running in the cronjob.
Hence my question is:
Is it possible in PHP and Wordpress to use Threaded Cronjob tasks which can run in parallel or be called separately?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Save_Post change Custom Post Type Post title to post id number I have a Custom Post Type with the slug of "sightings".
I do not need a post title, so I have removed the functionality - but now the posts are being saved as (no-title).
I read about the save_post functionality that can change the post title to something upon save? I hope thats correct.
Can someone help me write some code to achieve this? I have googled it, yes and also tried a couple of Stack Exchange snippets, but they dont seem to do anything.
Rob.
A: A very easy way to accomplish this would be to add something like this into your themes functions.php file:
function update_post(int $id, \WP_Post $post, bool $update)
{
// Case the post object to an array
$data = (array) $post;
// Set the title to the ID of the post
$data['post_title'] = $id;
// We need to remove the action to prevent an infinite loop
remove_action('save_post', 'update_post');
wp_update_post($data);
// Finally re-add the action hook
add_action('save_post', 'update_post', 10, 3);
}
add_action('save_post', 'update_post', 10, 3);
Notice that you can narrow down which post types to handle by using add_action('save_post_{$post->post_type}', 'update_post', 10, 3);.
So if you custom post type is called video then you would add the hook like this:
add_action('save_post_video', 'update_post', 10, 3);
Read more in the documentation:
*
*save_post().
*save_post_{$post->post_type}.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Only Admin receives email is there a suitable code for blocking all registered users' outgoing email but only the admin receives all emails. I need a send all emails to admin only situation.
A: Mail sent from WP uses wp_mail() function. There is a filter that you can use before the mail is sent to filter the arguments used in the wp_mail() function, including the $to value.
See https://developer.wordpress.org/reference/hooks/wp_mail/
Look at the example code on that page to get an idea of how to block (or redirect) all mail sent by wp_mail(). You could put your implementation of that in your Child Theme's functions file, or your own private plugin.
It is possible that a plugin or a theme might not use the wp_mail() function, using instead mail() or their own implementation of phpMailer (which wp_mail() uses).
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Display taxonomy terms when adding a link in the admin When you add a link in the admin and make a research, all post types are displayed, but I wondered if there is an easy way to display also taxonomy terms. It would be very useful.
Thanks!
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Show content from pages based on Current Date I am designing a site and trying to recreate this page structure https://www.britannica.com/on-this-day . For This I created a CPT named On-This-Day. Inside On this day post type there are two type of articles Parent is Day and month its child are the major events happend on that specific date. I completed this part but the only thing left is I want my on this day page to render the content from my CPT based on the current date. My staging site url https://wordpress-886233-3072476.cloudwaysapps.com/on-this-day/february-8/
https://wordpress-886233-3260398.cloudwaysapps.com/on-this-day/
And here are some Screenshots of everything. Any help is really needed as I am stuck.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hide empty categories on widget I excluded some products from woocommerce_product_query with this code:
function en_archive_products_by_rol( $query ) {
if (is_admin()) {
return;
}
$meta_query = (array)$query->get('meta_query');
$meta_query = array_merge( $meta_query,wpf_do_hide_product());
$query->set( 'meta_query', array_unique($meta_query) );
return $query;
}
}
add_action( 'woocommerce_product_query', 'en_archive_products_by_rol', PHP_INT_MAX );
It works fine, but I'm trying to hide empty product categories on filter widget and it keeps counting excluded products in each category. I'm using this code:
function exclude_empty_terms_widget( $terms, $taxonomies, $args, $term_query ) {
$new_terms = array();
if ( ! empty( $terms ) && in_array( 'product_cat', $taxonomies ) ) {
foreach ( $terms as $key => $term ) {
if ( $term->count > 0 ) {
$new_terms[] = $term;
}
}
$terms = $new_terms;
}
return $terms;
}
add_filter( 'get_terms', 'exclude_empty_terms_widget', PHP_INT_MAX, 4 );
Any ideas of what is wrong?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WordPress CPT archive page display sticky post first and then display the rest of the posts in same Query I'm having one Custom post type I have added a Sticky Option to that Custom Post Type. When I choose the post as sticky means it's not working for me.
I have tried the below code.
Please don't add this as a duplicate question, Here I can see a solution for this but they are having two queries passing I need this in one query. I don't need to pass two different queries. I need that in the same query.
Thanks in advance.
$sticky = get_option( 'sticky_posts' );
$query_args = [
'post_type' => $this->post_type,
'post_status' => 'publish',
'orderby' => 'post__in',
'tax_query' => [
'relation' => 'AND',
array(
'post_type' => $this->post_type,
'post__in' => $sticky,
),
array(
'post_type' => $this->post_type,
'post__not_in' => $sticky,
)
],
];
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Gutenberg list items nesting and creating invalid content errors I am trying to figure out why Gutenberg is creating nested lists instead of adding to the existing list, basically when the list block is selected I am able to make a single li element and then when trying to add another li element it creates a whole list nested in the first li element. Also pressing enter after creating the first li element has no effect, I would expect the action of pressing enter while creating a list would generate a new li element?
When I try to edit the block via HTML and manually add another li element it breaks the block and claims the content is invalid, an option to "attempt block recovery" is displayed but does not actually do anything or recover anything.
Has anyone experienced this issue? Is Gutenberg really this broken ( still )?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XAMMP MySql doesn't start I am running XAMMP 7.4.29 on Windows 10, where I am developing a wordpress website. This has been working fine until this afternoon, when I had to restart XAMMP and so Apache and MySql.
Apache server restarted as usual, but MySql failed to do it. The error message that is displayed is as follows:
18:49:40 [Apache] Attempting to start MySQL app...
18:49:40 [Apache] Status change detected: running
18:49:40 [mysql] Attempting to start MySQL app...
18:49:40 [mysql] Status change detected: running
18:49:40 [mysql] Status change detected: stopped
18:49:40 [mysql] Error: MySQL shutdown unexpectedly.
18:49:40 [mysql] This may be due to a blocked port, missing dependencies,
18:49:40 [mysql] improper privileges, acrash, or a shutdown by another method.
18:49:40 [mysql] Press the Logs button to view error logs and check 1
18:49:40 [mysql] the Windows Event Viewer for more clues
18:49:40 [mysql] If you need more help, copy and post this
18:49:40 [mysql] entire log window onthe forums
If I look at the log file I find:
2023-02-09 18:49:49 0 [Note] InnoDB: The first innodb_system data file 'ibdata1' did not exist. A new tablespace will be created!
2023-02-09 18:49:49 0 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2023-02-09 18:49:49 0 [Note] InnoDB: Uses event mutexes
2023-02-09 18:49:49 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2023-02-09 18:49:49 0 [Note] InnoDB: Number of pools: 1
2023-02-09 18:49:49 0 [Note] InnoDB: Using SSE2 crc32 instructions
2023-02-09 18:49:49 0 [Note] InnoDB: Initializing buffer pool, total size = 16M, instances = 1, chunk size = 16M
2023-02-09 18:49:49 0 [Note] InnoDB: Completed initialization of buffer pool
2023-02-09 18:49:49 0 [Note] InnoDB: Setting file 'D:\XAMPP php-7-4-29\mysql\data\ibdata1' size to 10 MB. Physically writing the file full; Please wait ...
2023-02-09 18:49:49 0 [Note] InnoDB: File 'D:\XAMPP php-7-4-29\mysql\data\ibdata1' size is now 10 MB.
2023-02-09 18:49:49 0 [Note] InnoDB: Setting log file D:\XAMPP php-7-4-29\mysql\data\ib_logfile101 size to 5242880 bytes
2023-02-09 18:49:49 0 [Note] InnoDB: Setting log file D:\XAMPP php-7-4-29\mysql\data\ib_logfile1 size to 5242880 bytes
2023-02-09 18:49:49 0 [Note] InnoDB: Renaming log file D:\XAMPP php-7-4-29\mysql\data\ib_logfile101 to D:\XAMPP php-7-4-29\mysql\data\ib_logfile0
2023-02-09 18:49:49 0 [Note] InnoDB: New log files created, LSN=11451
2023-02-09 18:49:49 0 [Note] InnoDB: Doublewrite buffer not found: creating new
2023-02-09 18:49:49 0 [Note] InnoDB: Doublewrite buffer created
2023-02-09 18:49:49 0 [Note] InnoDB: 128 out of 128 rollback segments are active.
2023-02-09 18:49:49 0 [Note] InnoDB: Creating foreign key constraint system tables.
2023-02-09 18:49:49 0 [Note] InnoDB: Creating tablespace and datafile system tables.
2023-02-09 18:49:49 0 [Note] InnoDB: Creating sys_virtual system tables.
2023-02-09 18:49:49 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2023-02-09 18:49:49 0 [Note] InnoDB: Setting file 'D:\XAMPP php-7-4-29\mysql\data\ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2023-02-09 18:49:49 0 [Note] InnoDB: File 'D:\XAMPP php-7-4-29\mysql\data\ibtmp1' size is now 12 MB.
2023-02-09 18:49:49 0 [Note] InnoDB: Waiting for purge to start
2023-02-09 18:49:49 0 [Note] InnoDB: 10.4.24 started; log sequence number 0; transaction id 7
2023-02-09 18:49:49 0 [Note] Plugin 'FEEDBACK' is disabled.
2023-02-09 18:49:49 0 [ERROR] Could not open mysql.plugin table. Some plugins may be not loaded
2023-02-09 18:49:49 0 [ERROR] Can't open and lock privilege tables: Table 'mysql.servers' doesn't exist
2023-02-09 18:49:49 0 [Note] Server socket created on IP: '::'.
So there seem to be two errors, but don't know what may have produced them.
I looked at some possible solutions in this forum, that suggest eliminating some files within the 'data' directory but this doesn't work for me.
Actually after having tried this the MySql error log file says that the database is corrupted:
2023-02-09 19:25:10 0 [ERROR] InnoDB: Page [page id: space=0, page number=316] log sequence number 604051665 is in the future! Current system log sequence number 300306.
2023-02-09 19:25:10 0 [ERROR] InnoDB: Your database may be corrupt or you may have copied the InnoDB tablespace but not the InnoDB log files. Please refer to https://mariadb.com/kb/en/library/innodb-recovery-modes/ for information about forcing recovery.
2023-02-09 19:25:10 0 [Note] Server socket created on IP: '::'.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Where's the Block Template Feature in WordPress? I'm working on developing a site for one of the Institutes under our organizational umbrella, and I've run into a situation where it'd be great to have a template with some blocks already in place that a user could add and then replace the placeholders with the relevant information. If you've used Joomla and Regular Labs' Content Templater extension, you know exactly what I'm talking about.
I thought this was a feature in Wordpress, but I'm either missing something obvious or it's not there. I know there's the reusable blocks feature, which is close. You have to convert to regular blocks first before editing the content, but this is prone to user error and I'd rather reduce the number of steps required to get the template onto the page and ready for the user's content.
I've tried looking, but the only thing I keep finding is the Site Editor that's in Beta, and not what I'm after. It seems like this would be such an obvious thing to have built in, I'm a little baffled that I can't find anything like it besides Reusable Blocks.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dealing with unknown option '--variant' when setting up a block environment I'm on windows 10 with npm version 8.1.1, and node version 16.13.0
Within Visual Studio Code, I am in my plugins directory at the terminal.
From the terminal when I type in npx @wordpress/create-block --variant dynamic learn01-dyn-block
and press enter, it first asks me...
Need to install the following packages:
@wordpress/create-block
Ok to proceed? (y)
and I press y on my keyboard to proceed. But then it says...
error: unknown option '--variant'
why is that?
I'm attempting to follow the example in the docs here.
Oddly when process the following into the terminal - npx @wordpress/create-block --help it displays my options, but no --variant.
Options:
-V, --version output the version number
-t, --template <name> project template type name; allowed values: "static", "es5", the name of an external npm package, or the path to a local directory (default: "static")
--namespace <value> internal namespace for the block name
--title <value> display title for the block and the WordPress plugin
--short-description <value> short description for the block and the WordPress plugin
--category <name> category name for the block
--wp-scripts enable integration with `@wordpress/scripts` package
--no-wp-scripts disable integration with `@wordpress/scripts` package
--wp-env enable integration with `@wordpress/env` package
-h, --help display help for command
*
*Is the docs outdated?
*How can I insure that I am building a dynamic block as opposed to a static block?
A: *
*From the docs https://developer.wordpress.org/block-editor/reference-guides/packages/packages-create-block/ I would say you have to provide template also for that option, though I never used it.
*I recommend you to get yourself more familiar with block development, it is very clear if block is dynamic or static, if it has php callback for rendering instead of save procedure in javascript, it is dynamic. Static blocks are recommended, while dynamic blocks are used where static HTML is not sufficient (i.e. dynamically provide data from database). Even then, it is recommended for the sake of better UI to use React - based block in edit function instead of <ServerSideRender>, which is slow. In reality, many developers choose to develop dynamic blocks because of insufficient knowledge or React and WordPress block development SDK. Famous ACF blocks plugin is based on the same principle.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using WP Query, I want to include all posts in category 1 as long as they are not also in category 2 $args = array(
'post_type' => 'product',
'meta_key' => 'sorting_weight',
'orderby' => 'meta_value_num',
'posts_per_page' => -1,
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => 81, // category 1, but for posts also in category 2 I want to exlcude
)
)
);
A: I think, you can try this type of code.
$args = array(
'post_type' => 'product',
'meta_key' => 'sorting_weight',
'orderby' => 'meta_value_num',
'posts_per_page' => - 1,
'order' => 'DESC',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => 81, // category 1
),
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'operator' => 'NOT IN',
'terms' => 82, // category 2
)
)
);
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using input_attrs() Multiple Times Within One Customizer Control Using input_attrs() Multiple Times Within One Customizer Control.
I want to be able to use the function input_attrs()
https://developer.wordpress.org/reference/classes/wp_customize_control/input_attrs/
With this type of code $this->input_attrs() And I want to be able to use the function multiple times...
Example 1:
<input type="text" value="blah1" <?php $this->input_attrs($1); ?>>
<input type="text" value="blah2" <?php $this->input_attrs($2); ?>>
The first example is not correct php. Do you know how to write this correctly?
Example 2:
<input type="text" value="blah1" <?php $this->input_attrs(); ?>>
<input type="text" value="blah2" <?php $this->input_attrs_2(); ?>>
If I do end up using a input_attrs_2() Do I also need my own function get_input_attrs_2() ?
A: You shouldn't need to call the input_attrs() method directly. Instead, rely on the add_control() method of the wordpress customizer object to generate the html inputs for your customizer settings. The add_control() method takes as its second argument an array of properties that allows you to set the label for the input, the section of the customizer where the input will be found, the type of input (text, checkbox, <select>, etc.), and more. A complete list of properties you can set via the second argument of add_control() can be found here. One of them is input_attrs. If you pass this property an array of name/value pairs, add_control() will include them as custom attributes and values on the html inputs it generates.
As a loose example of what this might look like when you put it all together:
add_action( 'customize_register', 'mytheme_customize_register');
function mytheme_customize_register( $wp_customize ) {
$wp_customize->add_setting( 'mytheme_mysetting', array(
'default' => '',
'sanitize_callback' => 'sanitize_text_field'
) );
$wp_customize->add_control( 'mytheme_mysetting', array(
'label' => __( 'My website user of the month', 'mytheme-textdomain' ),
'type' => 'text',
'section' => 'mysection',
'input_attrs' => array(
'my-custom-attribute-name' => 'my custom attribute value',
'foo' => 'bar'
)
));
}
A: In case anyone reads my question and wants an answer. To reproduce input_attrs() as many times as you want in a crude way all you need to do is define a variable each time in the class. For example public $inputattrs2 and then you are able to use the code echo esc_attr($this->inputattrs2); or echo $this->inputattrs2; along with your html in your class control and the add_control. This works for anything including text descriptions or html attributes.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using autocomplete with post_tag taxonomy on attachments How do I use autocomplete on the post_tag taxonomy that I added to my attachments?
Following the suggestion here, I added the post_tag taxonomy to my attachments:
function dod_add_tags_to_attachments() {
register_taxonomy_for_object_type( 'post_tag', 'attachment' );
}
add_action( 'init' , 'dod_add_tags_to_attachments' );
It works well, making the post_tag taxonomy available on each attachment. However, when adding tags in the media library, WP does not autocomplete the tags as it does in regular posts.
To restate the question, how do I get the autocomplete to work for the post_tag taxonomy in the media library?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I join post and postmeta twice? I'm trying to join the following tables
postmeta
meta_id
post_id
meta_key
meta_value
1
5000
_team_id
10000
2
10000
_enddate
2024-00-00
posts
ID
post_title
10000
Team Name
Currently, I'm using the following query
SELECT post_id, meta_key, meta_value, post_title
FROM postmeta
INNER JOIN posts ON meta_value = ID AND meta_key = '_team_id'
GROUP BY posts.post_author
I get the following:
post_id
meta_key
meta_value
post_title
5000
_team_id
10000
Team Name
How do I add the second meta_value, using the previous meta_value as the id? So that I get the following...
post_id
meta_key
meta_value
post_title
_enddate
5000
_team_id
10000
Team Name
2024-00-00
Any help would be very grateful.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Running plugin unit tests vs. integration tests? I'm finding it difficult to figure out how to run unit tests vs. integration tests. If I run phpunit in the directory of my plugin, it seems to spin up a whole temporary version of wordpress in /tmp. This seems like it would be needed to do integration tests with the rest of wordpress and not a unit test. I just want to test my php functions in isolation to make sure they return the right thing when passed specific arguments.
I don't develop with php so I'm finding the landscape pretty confusing and the blogs and other documentation I've come across isn't helping much. Thanks.
A: As you've found there's a whole raft of outdated, poor and convoluted information around unit testing in WP currently. However Josh Pollock, a well respected WordPress dev and Core contributor did a YouTube series on testing in Wordpress least year which I found very helpful.
As I've been on the unit testing in WordPress journey too, and here is a high level rundown of what I've found:
*
*As you may know phpUnit is the defacto PHP testing framework, and the majority of of the framework agnostic packages and tooling for PHP are somehow based upon it.
*Due to the nature of WordPress it is difficult not to call global functions from your code, which of course are not available without either spooling up an instance of WP or mocking them somehow. Further, the WP docs offer no discussion on different approaches, which is likely why most tutorials start by using the wp_cli to scaffold out the tests. I for one have that found the wp_cli
approach to not be very well documented, and very slow in practice, as an instance of WP and its database connection was spooled up for each test, which made the test quite slow. This was my experience anyway, and there may be ways to mitigate this. The WP approach also requires a separate DB to interact with your tests, as you want to be mindful not to accidentally corrupt any real data during a failed test.
*To avoid all this, you could write mocks for WP functions yourself, which is possible in simple use cases, however these quickly become tedious write and maintain for projects with any complexity. There two libraries that are often cited for this purpose:
*
*WP_Mock
*Brain Monkey
Of the two, WP_Mock has more GitHub stars, more recent commits, and is actively maintained by GoDaddy and 10up. By comparison Brain Monkey by Giuseppe Mazzapica, is also well reviewed, and Josh describes it as 'excellent' in his tutorial series. Brain Monkey however has seen less community adoption (based on stars), and no significant contributions in recent years. This may be because it is largely feature complete –– however being maintained by a solo dev is likely a contributing factor. In fairness to Giuseppe, he has been active on any in issues posted in the past year.
Another project to consider is Codeception, which describes itself as follows:
Codeception collects and shares best practices and solutions for testing PHP web applications. With a flexible set of included modules tests are easy to write, easy to use and easy to maintain.
Codeception can be thought of as a superset of PHPUnit, and according to the docs phpunit and Codeception test are almost entirely interoperable. Codeception supports a range of testing approaches including functional, unit and acceptance tests. This creates a happy path as your needs grow without having to worry about configuring something like Selenium. Finally, in addition to first class WordPress support, it also also supports Symphony, Laravel and others. Codeception's versatility and broad support make it a very attractive proposition.
For many projects Codeception is surely overkill, however, if you also use other frameworks your experience will be transferable. This said, I have seen reviewers who observe that Codeception's yml configuration is cumbersome to set up and difficult to learn - these reviews are dated however and may not reflect the current state of the framework.
Personally, Im just now exploring WP_Mock for my project, as of the three bears, it feels like it may be 'just right'.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: loop hierarchical custom post type, child pages only I need to query all pages of a custom post type that are children, not just children of a specific page. different way to say it is exclude all parent pages from a query of a custom post type.
never would've thought this was such a PITA
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: duplicating page templates I am not much of a coder other than basic html and css lol so I have spent days trying to find a solution to this....
an old developer had created custom page templates for this website that call certain filters for the products etc. and this template is applied on 5 pages with different content that is pulled based on 'terms'. The issue is it has a button link that goes to a certain Calendly booking page. So ALL 5 pages have the same buttons that go to that specific booking page. Ideally I want each of those 5 wordpress pages to go to a different corresponding Calendly booking page, so I thought I could duplicate the page template (calling the new one something else) and just change the link in that new template.
Problem I'm having is, it is still pulling the original template when I go into page source and look.
Is anyone able to help me accomplish this please and thank you!!!
A: When you duplicated the template, I assume that you gave the template file a new file name, and placed it in the same directory as the source. And that you changed the "Template Name" in the duplicated file. And then made changes to the new template file to change the code on the button to point to the desired page.
And then you can edit the page and specify the new template for that page.
And that you did this on a Child Theme, because a theme update will overwrite any changes you made to theme files.
Ask the googles/bings/ducks about Child Themes (there are plugins that will create one for you), and also about Templates and how they work. Some programming skills are needed to understand how templates work.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Have two domains point to the same content on a wordpress multisite I have a Wordpress Multisite installation with several domains and subdomains on it.
Everything works fine.
Now I'd like to add a new domain name I just bought, pointing to the same content as one of the existing domains on the Multisite.
(Incidentally, it's the "main" site on the network, which also serves as a Network manager).
(no I'm not concerned with SEO problems).
To this end, I have done two things:
*
*created an Alias server pointing to the domain I want to replicate (via Virtualmin). (This works very well outside of Wordpress.)
*added the new domain as one of the multisites on Wordpress.
The result of the above is that the new domain isn't treated as an alias at all, but as a new website whose content needs to be filled in.
Now, get this: If I only do point 1) above, Wordpress acts as if I am trying to sign in a new website onto the multisite, and takes me to the registration page (even though, registration is disabled).
(Unfortunately I cannot go back to having multiple single sites now...)
I hope I managed to explain the situation clearly. I feel like I should draw a picture!
Is there any good way out of this? Perhaps get Wordpress to disregard the auto-registration thing?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How To Convert External Image URLs To Own Website's Uploaded Images Automatically? I have a website with over 300 posts and initially I used to use external image URLs in my blogs instead of uploading it to my DB and using them.
Is there any way to automatically get all the external image urls on all 300+ posts, to be uploaded onto my website and use the uploaded media's urls instead of the external image urls?
To be clearer, for example, if I am using a Lion's image from wikipedia, with wikipedia's URL..... I want to automatically upload that image onto my website and use the uploaded lion image url instead of the wikipedia url.
A: You can use this plugin Auto Upload Images
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom Sort Order for Custom Post Type Taxonomy I have a custom post type - Demo Tours
And for that CPT I created a Custom Taxonomy - Demo Tour Categories.
Each Demo Tour may have one or more category.
Each category has Custom Field - Category Image/Video
On front end, the query gets all the custom taxonomy entries (Tour Categories) display the category Image and Description on the left, and the Demo Tours that belong to that category listed on the right.
Pretty basic and works like a charm.
The problem is, I must control the list order of Demo categories (and the demo tours that belong to them).
Now the orderby is by their ID.
But I want to add a Custom field - Order Number to Custom Taxonomy - Demo Categories, and on front end I want to display them depending on the Order Number.
Custom Fields created with ACF plugin
and the Custom Post Types created with Pods Admin plugin.
I have really spent a significant time on web to find a solution but nothing matches exactly what I need.
I believe the problem is my approach but can't really put my finger on the problem.
Please show me a way :)
Here is my code : (briefly)
first I get the terms :
$terms = get_terms(
array(
'taxonomy' => 'tour_category',
'hide_empty' => true,
)
);
then I loop them to show a header with Category names (like a menu)
foreach($terms as $term) {
echo ' <a class="demo_cat_link" href="#' . $term->slug . '">' . $term->name . '<li class="demo_cat"></li></a>';
}
then I display the categories on the left
$i = 0;
foreach ($terms as $terms => $term) {
$i++ != 0 ? $fClass = "fade" : $fClass = "" ;
$cat_id = $term->term_id;
$cat_video = get_field('featured_video', $term->taxonomy . '_' . $term->term_id );
$cat_order = get_field('tour_category_list_order', $term->taxonomy . '_' . $term->term_id );
<div class="loop_left_section">
<div class="tour_cat_thumb <?=$fClass?>">
<video class="demo_featured" width="620" autoplay="autoplay" loop="loop" muted="">
<source type="video/mp4" src="<?php echo $cat_video; ?>">
</video>
</div> <? // tour_cat_thumb ?>
<h2><?php echo $term->name; ?></h2>
<p><?php echo $term->description; ?></p>
</div> <? // loop_left_section ?>
and the demo tours on the right
<div class="loop_right_section">
<?php
$args = array(
'post_type' => 'demotours',
'tax_query' => array(
array(
'taxonomy' => 'tour_category',
'field' => 'slug',
'terms' => $term->slug,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
while($loop->have_posts()) : $loop->the_post();
$demo_tour_link = ( get_field('demo_tour_link', get_the_ID() ) ? get_field('demo_tour_link', get_the_ID() ) : "#" );
echo '<a href="'.$demo_tour_link.'" class="tour_link">
<div class="demo_tour_wrap">
<h3>' . get_the_title() . '</h3>
<p>'. get_the_excerpt() . '</p>
</div>
</a>';
endwhile;
}
?>
</div> <? // loop_right_section ?>
A: Use usort with a custom callback, like this:
function compare_term_order_numbers( \WP_Term $a, \WP_Term $b ) : int {
$order_number_a = get_field( 'order_number', $a );
$order_number_b = get_field( 'order_number', $b );
return strcmp( $order_number_a, $order_number_b );
}
usort($terms, 'compare_terms' );
Note that this assumes get_field returns a plain string, not an object, that each term has the order_number set and it isn't empty, and that $terms is an array of terms, not an error object or false/null.
More information at: https://www.php.net/manual/en/function.usort.php
A: Thanks to Tom J Nowell I found the solution. It was so simple that I felt a little shame not being able to figure it out myself.
First we need a function to 'insert' our custom taxonomy custom field to our WP Object. In this case the CPT is 'tour_category' and the Custom Field is 'order_number'
function terms()
{
return array_map(function($term) {
$term->order_number = get_field('order_number', $term);
return $term;
}, get_terms([
'taxonomy' => 'tour_category',
'orderby'=> 'order_number',
'order' => 'DESC'
]));
}
then, we use it in our loop:
$my= terms();
$num = array_column($my, 'order_number');
array_multisort($num, SORT_ASC, $my);
foreach($my as $term) { .... }
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Download button under all images WordPress I have a WordPress site with a huge number of images and I want to add the ability to download each one. they are contained in posts (one post contains 50-100 images). I tried using the "Files Download Delay" with the search by file extension feature, but the button doesn't appear. Perhaps there is a way to combine all the images of one post into a gallery and do it with each post (the number of posts is 500) or what other ways are there to use the script given below?
how can the idea be realized? Thank you
jQuery(".wp-block-image").each(function() {
var imageurl = jQuery(this).find("img").attr("src");
var download_html =`<div class="download-link">
<a href="javascript:void(0);"
id="download_nopurchased" class="click_download icon-download" data-
href="${imageurl}" download="${imageurl}" data-url="${imageurl}"><i
class="fas fa-download"></i> Download Now </a>
</div>`;
jQuery(this).append(download_html);
});
jQuery(".click_download").click(function() {
var file = jQuery(this).data("url");
var file_name = getFileName(file);
forceDownload(file,file_name);
});
function getFileName(str) {
return str.substring(str.lastIndexOf('/') + 1)
}
function forceDownload(url, fileName){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add custom user role into wordpress I added this code snippet to my function.php to create a user but after logging with this role I'm unable to edit the learndash course lessons quizzes...
add_role( 'learndash_content_manager', 'Learndash Content Manager', array(
'read' => true,
'manage_options' => true,
'edit_posts' => true,
'edit_others_posts' => true,
'edit_files' => true,
'publish_posts' => true,
'delete_posts' => true,
'delete_others_posts' => true,
'manage_categories' => true,
'edit_ld_courses' => true,
'edit_ld_lessons' => true,
'edit_ld_topics' => true,
'edit_ld_quizzes' => true,
'edit_ld_questions' => true,
'manage_links' => true,
'manage_options' => true,
'post_manage_options' => true,
'edit_published_ld_courses' => true
));
A: Example:
add_role('student', __(
'Student'),
array(
'read' => true, // Allows a user to read
'create_posts' => false, // Allows user to create new posts
'edit_posts' => false, // Allows user to edit their own posts
'edit_others_posts' => false, // Allows user to edit others posts too
'publish_posts' => false, // Allows the user to publish posts
'manage_categories' => false, // Allows user to manage post categories
)
);
Please also consider removing admin bar for certain users:
function remove_admin_bar() {
if (!current_user_can('administrator') && !is_admin()) {
show_admin_bar(false);
}
}
add_action('after_setup_theme', 'remove_admin_bar');
Take a look are your "ld" keys hooked right. If they are not, wp could clash.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I exclude the current post from the upcoming post query Summary: I have a page template with 3 queries.
*
*Current Exhibition
*Upcoming Exhibition
*Past Exhibition
The dates are custom fields. The problem I'm having is, how do I dynamically exclude the current post date from the upcoming exhibition query. After some digging around, I found I could use 'post__not_in'. Some examples below:
Example 1
$args = array(
'post_type' => 'post',
'posts_per_page' => 1,
'cat' => 14,
'post__not_in' => array( 71, 1 ),
'orderby' => 'date',
'order' => 'ASC',
'post_status' => 'publish',
);
$the_query = new WP_Query( $args )
;
Example 2
$args = array(
'numberposts' => 5,
'offset' => 0,
'category' => 7,
'post__not_in' => array( $post->ID )
);
$myposts2 = get_posts($args);
What is the proper usage for post not in to work with custom field dates? My code below -- Query Two "Upcoming Exhibitions"
<?php
/**
* The template for displaying archive pages.
*
* Template Name: Exhibition
*
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package boxpress
*/
get_header(); ?>
<?php // require_once('template-parts/banners/banner--artist.php'); ?>
<!-- // Query One -- pulls in current event -->
<?php
$exhibition_start_date = get_field('exhibition_start_date');
$exhibition_end_date = get_field('exhibition_end_date');
?>
<?php
wp_reset_query();
$exhibition_current_query = array(
'post_type' => 'exhibition',
'meta_key' => 'exhibition_start_date', // name of custom field
'orderby' => 'meta_value',
"order" => 'ASC',
"posts_per_page" => 1,
'meta_query' => array(
array(
'key' => 'exhibition_start_date',
'value' => date('Y-m-d'),
'compare' => '>=',
'type' => 'DATE'
)
),
);
$exhibition_current_loop = new WP_Query( $exhibition_current_query );
?>
<section class="section">
<div class="wrap">
<h2>Current Exhibitions</h2>
<?php if ( $exhibition_current_loop->have_posts() ) : ?>
<div class="l-grid l-grid--four-col">
<?php while ( $exhibition_current_loop->have_posts() ) : $exhibition_current_loop->the_post(); ?>
<div class="l-grid-item">
<div style="display: flex;" class="date">
<span class="start"><?php the_field('exhibition_start_date') ?></span> -
<span class="end"><?php the_field('exhibition_end_date') ?></span>
</div>
<h4><?php the_title() ?></h4>
<?php // get_template_part( 'template-parts/content/content-staff' ); ?>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
<?php wp_reset_query(); ?>
<!-- // Query Two -- pulls in upcoming event -->
<?php
wp_reset_query();
$exhibition_upcoming_query = array(
'post_type' => 'exhibition',
'orderby' => 'meta_value',
'order' => 'ASC',
'posts_per_page' => 3,
'meta_query' => array(
array(
'key' => 'exhibition_start_date',
'value' => date('Y-m-d'),
'compare' => '>',
'type' => 'DATE',
)
),
);
$myposts2 = get_posts($exhibition_upcoming_query);
$exhibition_upcoming_loop = new WP_Query( $exhibition_upcoming_query );
?>
<h2>Upcoming Exhibitions</h2>
<?php if ( $exhibition_upcoming_loop->have_posts() ) : ?>
<div class="l-grid l-grid--four-col">
<?php while ( $exhibition_upcoming_loop->have_posts() ) : $exhibition_upcoming_loop->the_post(); ?>
<div class="l-grid-item">
<div style="display: flex;" class="date">
<span class="start"><?php the_field('exhibition_start_date') ?></span> -
<span class="end"><?php the_field('exhibition_end_date') ?></span>
</div>
<h4><?php the_title() ?></h4>
<?php // get_template_part( 'template-parts/content/content-staff' ); ?>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
<!-- // Query Three -- pulls in past event -->
<?php
wp_reset_query();
$exhibition_past_query = array(
'post_type' => 'exhibition',
'orderby' => 'meta_value',
"order" => 'DESC',
"posts_per_page" => 8,
'meta_query' => array(
array(
'key' => 'exhibition_start_date',
'value' => date('Y-m-d'),
'compare' => '<',
'type' => 'DATE'
)
),
);
$exhibition_past_loop = new WP_Query( $exhibition_past_query );
?>
<h2>Past Exhibitions</h2>
<?php if ( $exhibition_past_loop->have_posts() ) : ?>
<div class="l-grid l-grid--four-col">
<?php while ( $exhibition_past_loop->have_posts() ) : $exhibition_past_loop->the_post(); ?>
<div class="l-grid-item">
<div style="display: flex;" class="date">
<span class="start"><?php the_field('exhibition_start_date') ?></span> -
<span class="end"><?php the_field('exhibition_end_date') ?></span>
</div>
<h4><?php the_title() ?></h4>
<?php // get_template_part( 'template-parts/content/content-staff' ); ?>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
</div>
</section>
<?php get_footer(); ?>
A: I think you are asking how to exclude the current exhibition from your upcoming exhibitions query.
If that is the case, simply insert the ID of the current exhibition into the query using 'post_not_in':
$exhibition_upcoming_query = array(
'post_type' => 'exhibition',
'orderby' => 'meta_value',
'order' => 'ASC',
'posts_per_page' => 3,
'post__not_in' => array( $exhibition_current_loop->posts[0]->ID ),
'meta_query' => array(
array(
'key' => 'exhibition_start_date',
'value' => date('Y-m-d'),
'compare' => '>',
'type' => 'DATE',
)
),
);
Hit me up if I am misunderstanding what you are after.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wordpress gutenberg block serverside rendering html elements not showing up import { registerBlockType } from '@wordpress/blocks';
import ServerSideRender from '@wordpress/server-side-render'
import {useBlockProps} from '@wordpress/block-editor'
registerBlockType('fsm/custom-logo-block',{
title:"Fsm Logo",
description:"Adres Eklemek İçin Kullanabilirsiniz.",
icon:"format-gallery",
category:"widgets",
attributes:{
width:"string",
heigth:"string"
},
edit:function({attributes,setAttributes}){
return (
<div {...useBlockProps()}>
<h1>Web Site Logo</h1> // this does not appear
<input placeholder='width' onChange={(e)={setAttributes({width:e.target.value})}}/>
<input placeholder='height' onChange={(e)=>{setAttributes({heigth:e.target.value})}}/>
<ServerSideRender block="fsm/custom-logo-block"/>
</div>
)
},
save:function({attributes}){
return null
}
})
<?php
function logoRender(){
$custom_logo_id = get_theme_mod('custom_logo');
$logo = wp_get_attachment_image_src($custom_logo_id,'full');
$alt = get_bloginfo("name");
if(has_custom_logo()){
return '<img class="logo" src="'.esc_url($logo[0]).'" alt="'.$alt.'"';
}
else{
return "<h1 class='found'>Logo Bulunamadı</h1>";
}
}
function fsm_gutenberg_blocks(){
wp_register_script('fsm-custom-logo-block',get_template_directory_uri().'/build/index.js',array('wp-blocks'));
register_block_type("fsm/custom-logo-block",array(
'render_callback' => "logoRender",
'editor_script' => 'fsm-custom-logo-block'
));
}
add_action('init','fsm_gutenberg_blocks')
?>
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add more than one menu for logged in members? I have the following code to show different menus to logged in members. I would like to add a second menu to be displayed when logged in, for a total of 3 menus, as there are two different menu areas for logged-in users.
function my_wp_nav_menu_args( $args = '' ) {
if( is_user_logged_in() ) {
$args['menu'] = 'menu-1';
} else {
$args['menu'], $args['menu'] = 'menu-3';
}
return $args;
}
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );
When using this code as-is, "menu-1" will display twice in the 2 areas. I can not figure out the syntax to add another line to include "menu-2". Can someone let me know what to change?
A: I suggest you use the theme_location options in WordPress. Assuming you have multiple locations for navigation menus what you could do is assign the two different menus to two different locations. Then adjust your theme templates to display the menu based on logged-in status rather than trying to add two menus to the same location. If you don't have custom theme locations then you can create them with the register_nav_menu function.
That would look like this:
add_action( 'after_setup_theme', 'register_my_menu' );
function register_my_menu() {
register_nav_menu( 'logged-in-menu', __( 'Logged In Menu One', 'theme-slug' ) );
}
Then you will need to edit the theme template which has the nav menus which most likely be located in the following folder: wp-content/themes/theme-name. (You should be using a child theme to make these changes if you aren't already) In that template, there should be a wp_nav_menu() function call that outputs the menu. To show or hide conditionally based on logged-in status it would look something like this:
<div class="header-nav-menu-one>
<?php if(is_user_logged_in()){
wp_nav_menu(array('theme_location' => 'logged-in-menu',...other args))
} ?>
</div>
<div class="regular-menu">
<?php wp_nav_menu(array('theme_location' => 'primary',...other args)) ?>
</div>
Not sure that is the best solution but I think it would accomplish what you are trying to accomplish.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom taxonomy with custom meta value is not sorting correctly (query returns the same value for orderby regardless of sort column click) I have a weight class category, where I want to sort by weight so Heavyweight shows at the top, and Flyweight at the bottom. I have created a custom meta field called 'weight' where I store an int corresponding to the weight for the respective weight class.
Here is the code where I setup the custom tax:
register_taxonomy( 'weight-class', 'ratings',
array(
'labels' => array(
'name' => 'Weight Class',
'singular_name' => 'Weight Class',
'menu_name' => 'Weight Classes',
'all_items' => 'All Weight Classes',
'add_new' => 'Add A Weight Class',
'add_new_item' => 'Add New Weight Class',
'edit_item' => 'Edit Weight Class',
'view_item' => 'View Weight Class',
'view_items' => 'View Weight Classes'
),
'hierarchical' => true,
'show_admin_column' => true
)
);
Here is the code where I setup the custom meta data to be created and updated:
function cb_add_term_fields( $taxonomy ) {
echo '<div class="form-field">
<label for="weight">Maximum Weight (LBS)</label>
<input type="text" name="weight" id="weight" />
<p>Must be a number. Used for sorting purposes only.</p>
</div>';
}
add_action( 'weight-class_add_form_fields', 'cb_add_term_fields' );
function cb_edit_term_fields( $term, $taxonomy ) {
$value = get_term_meta( $term->term_id, 'weight', true );
echo '<tr class="form-field">
<th>
<label for="weight">Maximum Weight (LBS)</label>
</th>
<td>
<input name="weight" id="weight" type="text" value="'.esc_attr($value).'" />
<p class="description">Must be a number. Used for sorting purposes only.</p>
</td>
</tr>';
}
add_action( 'weight-class_edit_form_fields', 'cb_edit_term_fields', 10, 2 );
function cb_save_term_fields( $term_id ) {
update_term_meta(
$term_id,
'weight',
sanitize_text_field( $_POST[ 'weight' ] )
);
}
add_action( 'created_weight-class', 'cb_save_term_fields' );
add_action( 'edited_weight-class', 'cb_save_term_fields' );
Here is the code where I setup Weight as a custom sortable column:
add_filter('manage_edit-weight-class_columns', 'add_weight_column' );
function add_weight_column( $columns ){
$columns['weight'] = __( 'Weight' );
return $columns;
}
add_filter( 'manage_edit-weight-class_sortable_columns', 'add_weight_column_sortable' );
function add_weight_column_sortable( $sortable ){
$sortable[ 'weight' ] = 'weight';
return $sortable;
}
add_filter('manage_weight-class_custom_column', 'add_weight_column_content', 10, 3 );
function add_weight_column_content( $content, $column_name, $term_id ){
if( $column_name !== 'weight' ){
return $content;
}
$term_id = absint( $term_id );
$weight = get_term_meta( $term_id, 'weight', true );
if( !empty( $weight ) ){
$content .= esc_attr( $weight );
}
return $content;
}
add_action( 'pre_get_posts', 'weight_column_orderby' );
function weight_column_orderby( $query ) {
echo "<script>console.log('" . $query->get( 'orderby' ) . "');</script>";
if( ! is_admin() )
return;
$orderby = $query->get( 'orderby' );
if( 'weight' == $orderby ) {
$query->set('meta_key','weight');
$query->set('orderby','meta_value_num');
}
}
Everything works great until I went to test the sort function on my taxonomy. My problem currently resides with this piece of code:
add_action( 'pre_get_posts', 'weight_column_orderby' );
function weight_column_orderby( $query ) {
echo "<script>console.log('" . $query->get( 'orderby' ) . "');</script>";
if( ! is_admin() )
return;
$orderby = $query->get( 'orderby' );
if( 'weight' == $orderby ) {
$query->set('meta_key','weight');
$query->set('orderby','meta_value_num');
}
}
As you can see, I am using a quick script tag to print out the value of orderby in the query. No matter what column I click to sort on the taxonomy list page, the script tag above always returns "menu_order title". I click on slug or description and still get this. Is there a setting I missed somewhere? Any help would be appreciated! Thanks!
A: pre_get_posts is an action hook used for modifying the arguments passed to the WP_Query class, and if you're filtering the posts in the list table at wp-admin/edit.php, then yes, you would use that hook.
However, since you're filtering the terms in the list table at wp-admin/edit-tags.php, then the hook that you should have used is pre_get_terms, which can be used to modify the arguments passed to the WP_Term_Query class.
*
*That class is used by get_terms() which is used by the class which renders the terms list table.
But then, I don't know for sure why ( maybe it's a bug in WordPress core? ), but when sorting by meta value, i.e. when orderby is meta_value_num, meta_value, or a key in a meta_query array, it seems we need to use the parse_term_query hook instead, which runs before pre_get_terms.
And here's an example you can try, and note that unlike WP_Query, WP_Term_Query doesn't have a get() or set() method, hence I directly accessed/modified the query_vars property:
add_action( 'parse_term_query', 'weight_column_orderby' );
function weight_column_orderby( WP_Term_Query $query ) {
// Check whether we are at wp-admin/edit-tags.php?taxonomy=weight-class
if ( ! is_admin() ||
! function_exists( 'get_current_screen' ) ||
'edit-weight-class' !== get_current_screen()->id
) {
return;
}
$taxonomies = (array) $query->query_vars['taxonomy'];
// Modify the args, if `weight` is the `orderby` value, and that the query
// is for your custom `weight-class` taxonomy.
if ( 'weight' === $query->query_vars['orderby'] &&
in_array( 'weight-class', $taxonomies, true )
) {
$query->query_vars['meta_key'] = 'weight';
$query->query_vars['orderby'] = 'meta_value_num';
}
}
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I add a check and not send an auto-reply to certain comments if the user fills in a custom field? I'm using custom fields in the comment form "Did you like this book?" and "yes" and "no" values. I want to send 2 different auto-replies to a comment, if the user selects "yes" then the response is "Thank you for your kind recognition, customer's satisfaction is always our goal." and if "no" then the auto answer is "We'll strive to do better." I would appreciate any of your help...
//And this is how I send an auto reply to a comment
add_action( 'comment_post', 'author_new_comment', 10, 3 );
function author_new_comment( $comment_ID, $comment_approved, $commentdata ){
$comment_parent = (int) $commentdata['comment_parent'];
// If a new comment is a reply to another comment, don't do anything
if ( $comment_parent !== 0 ) {
return;
}
//How do I add a response if the comment contains the value of the [likebook ] meta field???
if( !empty( $_POST['likebook'] ) {
return;
}
$commentdata = [
'comment_post_ID' => $commentdata['comment_post_ID'],
'comment_author' => 'admin',
'comment_author_email' => '[email protected]',
'comment_author_url' => 'http://example.com',
'comment_content' => 'Thank you for your kind recognition, customer satisfaction is always our goal.',
'comment_type' => 'comment',
'comment_parent' => $comment_ID,
'user_ID' => 1,
];
wp_new_comment( $commentdata );
}
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I look at/edit what's being sent to post.php when I hit the publish/update button? I want to change the content of what's being sent to post.php when I click on the publish/update button.
Specifically I want to append content using javascript.
So let's say I'm clicking on update, I can see that this sends a request to post.php with parameters (presumably including the content of the post).
How can I modify this before it gets to post.php?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing my URL in General Settings cause the site to crash I installed wordpress on ubuntu using this guide
I uploaded my backup and everything went fine until I tried to use my domain. Whenever I try to change from http://20.210.236.41 to my domain http://mostmarv.com/ I instantly lose access and have to login via ssh and change the domain back in the Mysql table, e.g.
UPDATE wp_options SET option_value = 'http://20.210.236.41' WHERE option_name IN ('siteurl', 'home');
I can then access again.
I tried using the plugin really simple ssl and then lost access to my homepage. I'm going crazy, anyone have any ideas?
A: The first domain listed in your question has the wp-admin slug, the 2nd doesn't. You shouldn't be making that change. Hopefully it was just a typo, however if that's what you're actually doing that is likely your problem.
Also, you should be changing all instances of the old domain http://20.210.236.41 to the new domain WITH SSL https://mostmarv.com/. That way you don't need to use any SSL plugins.
If you can use WP-CLI this will work: wp search-replace http://20.210.236.41 https://mostmarv.com
Another option is to make the change in the dev server backend settings, download that db and then upload it to the new site.
One last option to get you up and running would be to add these lines to your wp-config.php file:
define('WP_HOME', 'https://mostmarv.com');
define('WP_SITEURL', 'https://mostmarv.com');
These 2 options could let you at least get the site live, but could cause a lot of problems though because WordPress uses the URL string an many other places thoughout the site. So you're better off using WP-CLI or other software that will search for every instance of the older address or URL.
TLDR : Just changing your home and siteurl is not enough to completely transfer your site from one domain to another. You need to find all references to the old address.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Need Help With Making Full-Width Template for Blog Posts (common methods aren't working) I've been researching this one for a while and can't seem to find the solution. But, I'd like to have a selectable template that I can use for certain blog posts to make them full-width by not displaying the sidebar while keeping the header, footer, and comments. My theme (Coral Dark) came with a pages-full-width.php template that accomplishes exactly this for pages. But, I have no templates to choose from for regular posts.
I've tried to create one myself by copying the single.php file and removing the <?php get_sidebar(); ?> code, but this does not work. I've also tried to add this to custom CSS (changing the post ID) as someone suggested, but no result there either:
.single-author .site-content,
.postid-4553 .site-content,
.postid-4253 .site-content
{
flex: 0 0 100%!important;
max-width: 100%!important;
padding-right: 0px!important;
}
I also tried the Fullwidth Templates for Any Theme & Page Builder plugin which almost gave me exactly what I need, but no matter which setting I use, it eliminates the comments section.
I'm not quite sure, but I think the issue is my theme doesn't seem to refer to the sidebar as such, and instead seems to call it widget-area egrid. Not sure if that's accurate, but would make sense as to why simply removing the <?php get_sidebar(); ?> on these template tutorials isn't working.
Here's an example of a post that I'd like to apply this custom template for, just to eliminate the sidebar/widgets so the post is full width, but keeping the header, footer, and comments:
https://lordkayoss.com/2022/02/28/equipment-chronicles-chasing-quality-on-youtube/
Can someone help?
A: Got this working on a test site by downloading the coral dark theme and making a child theme for it. Making a child theme might seem a little daunting if you've never made wordpress themes before, but it's the most sustainable and overall best way to do this in my opinion. And it's actually pretty easy. I will go through the steps I took. You can find background information about child themes in this section of the theme developer handbook.
First, create an empty folder on your computer and name it coral-dark-child.
Next create a text file inside that folder called style.css. Open that file and copy/paste the following:
/*
Theme Name: Coral Dark Child
Template: coral-dark
*/
@media (min-width: 768px) and (max-width: 1024px){
.full-width-post.tablet-grid-70 {
width: 100%;
}
.full-width-post.tablet-push-30{
left: 0;
}
}
@media (min-width: 1025px){
.full-width-post.grid-70{
width: 100%;
}
.full-width-post.push-30 {
left: 0;
}
}
*
*The heading at the top of the file tells wordpress this is a child theme, and that it needs to look at the "template" or parent theme, Coral Dark, for most of the necessary files.
*The tablet-grid-70 and grid-70 css classes are restricting the content to 70% of the screen width on medium and large screens. We are going use our own full-width-post class in our custom template to override this, setting elements to 100% width when they have both a 'grid-70' class and a 'full-width-post' class.
Now create a another text file in the coral-dark-child folder called functions.php. Copy/paste the following:
<?php
function coral_dark_child_enqueue_styles(){
$theme = wp_get_theme();
/*parent theme stylesheet*/
wp_enqueue_style(
'coral-dark-style',
get_template_directory_uri() . '/style.css',
array(),
$theme->parent()->get( 'Version' )
);
/* our child theme stylesheet */
wp_enqueue_style(
'coral-dark-child-style',
get_stylesheet_uri(),
array( 'coral-dark-style')
);
}
add_action( 'wp_enqueue_scripts', 'coral_dark_child_enqueue_styles' );
*
*Here we use wp_enqueue_style to add the css we defined in style.css to the site. We have to call it twice, once to load the parent theme css, then again to load our child theme css.
Lastly, we'll make a custom page template that will actually display our full-width posts. You had the right idea when you copied the single.php file, that's basically what we're going to do here. But first, we're going to make another folder inside the coral-dark-child folder called page-templates. Inside page-templates we're going to make another text file called full-width.php. The overall folder structure now looks like this:
coral-dark-child
-style.css
-functions.php
-page-templates
-full-width.php
Now in full-width.php copy/paste the following:
<?php
/**
* Template Name: Full-width
* Template Post Type: post
*/
get_header(); ?>
<div id="primary" class="content-area egrid full-width-post <?php coral_dark_column_class('content'); ?>">
<main id="main" class="site-main" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'single' ); ?>
<?php $parg = array(
'prev_text' => esc_html__( 'Previous post', 'coral-dark' ),
'next_text' => esc_html__( 'Next post', 'coral-dark' ),
'screen_reader_text' => esc_html__( 'Post navigation', 'coral-dark' )); ?>
<?php the_post_navigation($parg); ?>
<?php
// If comments are open or we have at least one comment, load up the comment template
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
?>
<?php endwhile; // end of the loop. ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_footer(); ?>
*
*This is almost an exact copy of single.php from the parent theme.
*The commented-out header sets the name this template will be identified by on the "edit post" screen in the admin area. The "Template Post Type" line tells wordpress this template is for posts specifically, as opposed to pages.
*One difference from single.php is that we have removed the get_sidebar() call because there is no room for the sidebar in the full-screen layout.
*The other difference is that we have added the "full-width-post" class to the outermost <div> (the one with id "primary"). This means the css we wrote earlier can target this div, telling it to take up the full width when this template is active.
At this point, you should have a working child theme. Create a zip file of this folder and upload it your site via Appearance->Themes->Add New. Activate the child theme. Then, edit the post you want to make full-width. Click the link to the right of 'template' in the right hand menu and you should get a dropdown that allows you to select the "full-width" template. You might have to clear your browser cache to see the change take effect on the front end.
The beauty of this being a child theme is that if it's not looking right or anything goes wrong at any point, you can just revert to parent theme. Also it won't interfere with updating the parent theme. Hope this helps.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Uploaded files fail to link I upload 24 small html files once a week. They are nearly identical, with only a few printed values on the html sheets being different. I delete the 24 previous files which were properly linked and displayed. I then clear the cache. When I upload the new files, they might or might not automatically link. I have tried reloading the exact same files, and the linking fails. To get them to display, I have to manually delink and relink them from the page on which they are displayed. I can find no reason why it fails.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: 'random_password' filters not taking effect The function below is intended to filter WordPress' default password generation however when either adding a user or resetting the password, it doesn't apply it. What am I missing?
function wpgenerapass_generate_password( $extra_special_chars = false ) {
$chars = 'abcdefghijklmnopqrstuvwxyz';
$chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$chars .= '0123456789';
$chars .= '!@#$%^&*()';
if ( $extra_special_chars ):
$chars .= '-_ []{}<>~`+=,.;:/?|';
endif;
$wpgenerapass_password = ''; // Initialize the password string
$password_length = 8;
for ( $i = 0; $i < $password_length; $i += 1 ) {
$wpgenerapass_password .= substr( $chars, wp_rand( 0, strlen( $chars ) - 1 ), 1 );
}
return apply_filters( 'random_password', $wpgenerapass_password );
}
A: I think, your PHP syntax is wrong. Try these,
function wpgenerapass_generate_password( $password, $length, $special_chars, $extra_special_chars ) {
$chars = 'abcdefghijklmnopqrstuvwxyz';
$chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$chars .= '0123456789';
$chars .= '!@#$%^&*()';
if ( $extra_special_chars ) {
$chars .= '-_ []{}<>~`+=,.;:/?|';
}
$wpgenerapass_password = ''; // Initialize the password string
$password_length = 8;
for ( $i = 0; $i < $password_length; $i += 1 ) {
$wpgenerapass_password .= substr( $chars, wp_rand( 0, strlen( $chars ) - 1 ), 1 );
}
return $wpgenerapass_password;
}
add_filter( 'random_password', 'wpgenerapass_generate_password', 99, 4 );
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Custom product sorting archive page I would like to create a sorting products custom.
The result I would like is the following
*
*all featured products
*Most sold products in the last year
*All other products.
Is it possible to do everything programmatically?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to upscale a media library original image to the nearest whole pixel in Wordpress? I noticed today while manually regenerating thumbnails for images in the media library that at least one would not generate thumbnails for those sizes that had the same width as the image.
In fact, there was a message saying the thumbnail would be larger than the original image even though the listed width of the image and the width of the thumbnail matched.
For example: the dimensions of the original image were listed as 1500x323, the thumbnail size as 1500x300, but when attempting to renegenerate thumbnails, a message popped up for this thumbnail size saying it would be larger than the original image.
When I looked at the original image a bit closer, I found that the actual width of the image in question was 1499.99px.
Long story short, has anyone encountered this before and is there a fix?
More specifically, a fix that doesn't involve downloading, resizing, and uploading the image which would mean I'd have to update the image links?
I've only found this with one image so far, and I'm wondering what can be done to address this instance and proactively handle any others.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to fix Fatal error: Cannot redeclare get_cli_args() in class-wp-importer.php I'm getting the following error:
Fatal error: Cannot redeclare get_cli_args() (previously declared in C:\xampp\htdocs\wordpress\wp-admin\includes\class-wp-importer.php:276) in C:\xampp\htdocs\wordpress\wp-admin\includes\class-wp-importer.php on line 276
function get_cli_args( $param, $required = false ) {
$args = $_SERVER['argv'];
if ( ! is_array( $args ) ) {
$args = array();
}
// ...
}
How do I fix it?
A: Are you somehow including wp-admin\includes\class-wp-importer.php using include or require? That may cause the error of get_cli_args() function declared twice.
If that is the case, then you better use include_once or require_once.
Also, perhaps you should test your installation by disabling all the plugins and any custom theme. Then activate the theme and test WordPress. Then activate one plugin at a time and test each time to see if the error appears. This will show if this error is caused by any plugin or theme.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Restrict Image Sizes and Dimensions when Uploading via the WP Mobile App I restrict image uploads by file size and dimensions on my client's websites using 'wp_handle_upload_prefilter'.
However, it appears this function is not called when using the WordPress.com mobile app. Authors who use this mobile app method for posting are allowed to upload any size and dimensions via the media library and "featured image" sections.
I assume the mobile app uses the REST API, rather than conventional frontend code. I haven't been able to find any filters for uploads using the REST API. Does anyone know of a workaround?
I understand there are methods of reducing overall file upload sizes across WordPress. This is not a question for the 'upload_size_limit' filter. I restrict both file size and image height/width for images. I also implement a different file size restriction for audio files, etc. I've exhausted research in finding a way to stop my authors from circumventing these restrictions using the WP app, which I assume uses REST. I do not want to prohibit them from using it though.
Oh, I should mention. We are NOT hosted on wp.com. We are using the app to login to our hosted website.
A: Try this code in function.php I hope this help.
add_action( 'rest_api_init', 'set_image_dimension_limit' );
function set_image_dimension_limit() {
add_filter( 'wp_handle_upload_prefilter', function( $file ) {
$mimes = array( 'image/jpeg', 'image/png', 'image/gif' );
if( !in_array( $file['type'], $mimes ) )
return $file;
$img = getimagesize( $file['tmp_name'] );
$maximum = array( 'width' => 500, 'height' => 700 );
if ( $img[0] > $maximum['width'] )
$file['error'] =
'Image too large. Maximum width is '
. $maximum['width']
. 'px. Uploaded image width is '
. $img[0] . 'px';
elseif ( $img[1] > $maximum['height'] )
$file['error'] =
'Image too large. Maximum height is '
. $maximum['height']
. 'px. Uploaded image height is '
. $img[1] . 'px';
return $file;
} );
}
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Split Million WordPress Post's Into Multiple Database Server Say I have 50,000 posts in my current WordPress installation. May be it will grow more than 5,00,000 post's in the future. Now I wanna Scale the database.
I wanna put ,
1-50,000 posts > database server 1
50,001- 1,00,000posts > database server 2
1,00,001- 1,50,000 > database server 3
N posts - N posts > database server N
And, when I will go to WordPress dashboard, I can see the total post count .. combined 3 database post ... Say 1,50,000 post's... Also, when an user will browse my site.... Different posts will fetch from different database.... (Only Read)....
Now, (write query)-
When I will write post... From WordPress admin, the post will get stored in another database server. Now, If I see ... Write Database server reached 60,000 or 70,000 posts ... I Will simply put this server in 'read' database cluster....
I will get another server for "write" , again 60,000 or 70,000 posts ...simply put it 'read' database cluster....
Like this N....
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to change mobile menu (toggle) icon in Wordpress - Full Site Editing? How to change mobile menu (burger) icon on Wordpress 6 using their new full site editing feature or possibly with some plugin?
I would like to replace their default burger and close icons to add Lottie animation but all I'm finding is how to do that in Elementor and Oxygen, but I'm not using those page builders, I'm using Wordpress FSE...
Any tips on this?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alternate Styling of Custom Block without Javascript, Get Block Count on Page I have a custom block being created in the block editor. Since the iterations and order of it can vary and the amount of siblings in between will fluctuate, I cannot use the typical CSS selectors to alternative a style of it for every instance it is on the page.
A simplified version of the markup that gets split out:
<article>
<div class="spacer"></div>
<div class="custom-block"></div>
<div class="spacer"></div>
<div class="custom-block"></div>
<div class="custom-block"></div>
<div class="spacer"></div>
<div class="custom-block"></div>
<div class="spacer"></div>
<div class="custom-block"></div>
<div class="custom-block"></div>
<div class="custom-block"></div>
<div class="spacer"></div>
<div class="custom-block"></div>
<div class="spacer"></div>
</article>
I would like every other instance of the div.custom-block to have a red border. Using something like nth-child or nth-of-type in CSS will not give me the results I want because the div.custom-block will almost always have siblings, a dynamic number of siblings, that I cannot always know the amount of.
But I do want the div.custom-block elements to alternate in styling, regardless of siblings.
I realize that after the page is rendered, I can use Javascript to accomplish this. I was hoping for something either CSS based, or PHP based on the server side.
Is it possible to get the count of which instance the custom block is being used? So I could say
$blockCount = // GET # OF WHICH BLOCK INSTANCE THIS IS ON THE PAGE
if($blockCount % 2 == 0) {
// give it a new class or styling or whatever I want here
}
https://jsfiddle.net/fujvw71b/
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to import term_meta in wordpress using wp_cron I have imported cities as term named as sf-cities I'm trying to add countries name as term meta I have attached sample of my code.
add_action( 'event_notification', 'import_countries', 10, 0 );
function import_countries(){
$response = wp_remote_get('https://raw.githubusercontent.com/russ666/all-countries-and-cities-json/master/countries.json');
$response_body = wp_remote_retrieve_body( $response );
$countries = json_decode($response_body);
$last_id = 0;
$terms = get_terms( array(
'taxonomy' => 'sf-cities',
'hide_empty' => false,
));
$count = 1;
foreach($countries as $country => $cities) {
foreach($cities as $city) {
$term = get_term_by('name', $city, 'sf-cities');
if( $count == 1000 ) {
$count = 1;
usleep(500);
}
if(!empty( $term )) {
if( $term->term_id > 220 ) {
if( empty( get_term_meta( $term->term_id , 'country', true) )) {
add_term_meta( $term->term_id ,'country', $country );
} else {
update_term_meta( $term->term_id ,'country', $country );
}
}
$last_id = $term->term_id;
} else {
continue;
}
$count++;
}
}
return $last_id;
}
Even it was working in the json file there are 80k records in there. Is there any other possibility to add term meta value without cron job.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WordPress not remembering old slugs for pages I have several WordPress sites working under different domains, but hosted on the same server.
I noticed that most of them will remember the old slug if changed. So it redirects to the new one if accessed. However, some of them wont do that despite being the same WordPress version.
Why is that? How can I fix it?
Note: I just noticed the only difference between the sites that remember and those that wont is that, for the former I have posts whereas for the latter I have fixed pages.
A: WordPress keeps track of post slug change with wp_check_for_changed_slugs() function. The old slugs are saved in wp_postmeta table with _wp_old_slug meta_key and later redirects to current URL with wp_old_slug_redirect() function.
That's why even after changing a post's slug, you get redirected to the correct post.
However, WordPress doesn't do this by default with pages (or any hierarchical posts).
It's still possible to change this behaviour by hooking into post_updated action and replicate wp_check_for_changed_slugs() function for pages (or any hierarchical posts) and then implementing the redirect logic using old_slug_redirect_url hook.
However, this is not recommended.
The main reason is: pages may have multiple levels (hierarchical). For example, a child page can be page_a/child-1 and another child page page_a/child-2 (there can be many more, with multiple levels).
Now, changing page_a slug affects both child-1 and child-2 pages. So to implement this properly, while visiting both child-1 and child-2, WordPress will have to check for first child-1 or child-2 slug change, and then page_a parent slug change. This sort of multi level checks will slow down WordPress for hierarchical posts or pages.
You'll find a similar discussion in WordPress.org support.
If you still need this, it's better to use a redirect plugin and manually add the redirect for pages with old permalinks.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to configure the request language WP_Query wpml Why the option "lang" does not work locked WP_Query ?
$args = array(
"post_type" => $_POST["art"],
"post_status" => "publish",
"order" => "DESC",
"orderby" => "date",
"lang" => $_POST["art_lang"],
'search_prod_title' => $_POST["term"],
"posts_per_page" => -1
);
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add Gutenberg editor on frontend page? I have a textarea on a public-facing page. I want to add Gutenberg editor to that textarea. I searched the official documentation but couldn't find anything. Any information will be helpful.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to save a post to a Custom post type and copy the information to another Custom post type? I used the Jet Engine plugin to create the first Custom Post Type called registration, the Post Type Slug called registration, and the Rewrite Slug called registration-add.
The first Custom Post Type called record has some meta fields called:
First Meta Field is:
Label: ENTRY Date
Name/ID: date-entry
Object type: Field
Field type: Date
Save as timestamp
The second Meta Field is:
Label: ENTRY TIME
Name/ID: hour-entry
Object type: Field
Field type: Time
The second Custom Post Type is called output_record, the Post Type Slug is called output_record, and the Rewrite Slug is called output-add-record.
The second Custom Post Type called output_register has some meta fields called:
First Meta Field is:
Label: ENTRY Date (EXIT RECORD)
Name/ID: date-entry-exit
Object type: Field
Field type: Date
Save as timestamp
The second Meta Field is:
Label: ENTRY TIME (EXIT RECORD)
Name/ID: hour-entry-exit
Object type: Field
Field type: Time
I am using a form plugin that publishes the post in the first Custom Post Type called record and that post is also saved in the Second Custom Post Type called record_output, you will wonder why, it is very simple it is a record where someone enters, and there must be a trace, but if it is going to leave, there must be another custom post type where the same information is that will later be edited to go from entering to leaving, that is, each post is an "entry and exit record". I just need that when it posts to that record custom post type it also posts to output.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to figure out correct wp_options to have autoload='yes' I have a website that has suddenly become slow. I don't know what caused the change. I haven't installed new plugins, and I don't think I recently updated any plugins. Upon inspection with Query Monitor, I can see that there are about 15,000 queries per page. Most of the queries (14K+) are repeated queries to wp_options
SELECT option_name, option_value
FROM wp_options
WHERE autoload = 'yes'
Is the cause of these queries that certain rows that are supposed to have autoload='yes' do not? How can I figure out which rows should have autoload 'yes' vs 'no'
I tried copying the autoload 'yes' values from another website, and I was able to lower the total number of queries to 8.5K like this. However the website isn't any faster.
Any advice on debugging this issue or somehow "resetting" the autoload values of the wp_options table?
A: WP-Rocket was deactivated, but the wp-content/object-cache.php file was still present. This file redefined the wp_cache_add in such a way that the method didn't work, so all requests to get a single option value were resulting in a query to the wp_options table.
I deleted the wp-content/object-cache.php file and the page response time dropped to 2 seconds from a peak of 15 seconds, and the total number of queries to 288 from a peak of 15,000.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Batch Scanning and Deleting Empty WordPress Posts I found a solution, How To Delete Post's With Empty Content Using WP-CLI. I am Looking For a SQL Query Version That Will Delete All Post's Eith Empty Content.
Here Is the WP-CLI Version-
wp post delete $(wp db query "SELECT ID FROM $(wp db prefix --allow-root)posts WHERE post_content='' AND post_title=''" --allow-root | tr '\r\n' ' ') --force --allow-root
I want A SQL QUERY Version Of this, Pls
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to retrieve Users (Not logged in) through WP Rest API We are able to retrieve Rest API results of our WP database, running a Learndash plugin.
We can retrieve details while not logged into the WP site, although limited (10 records or so).
While logged in though or not logged in, if we try the application password, it produces a 404 error and we cannot obtain any other records. The site has close to 900 users.
We can obtain other records nicely with the application password, while not logged in, using other endpoints.
Any ideas?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Working with Shortcode, AJAX, Elementor it's been days for me to work and did some research about it.
I have this page that build in Elementor. Part in the page, is a list of images with custom attribute.
For example, <img data-ch="1021" src="some random.jpg">
When user click the image, it will show a chatroom on specific div in the page. Chatroom is a shortcode. So I used AJAX to work with it but the shortcode seems not working. It shows only html but the overall functionality doesn't work.
Sample shortcode - [chatroom_img id="1021" title="Chatroom 1021"] and so on.
I tried the apply_filter, adding the shortcode to the single post of channel but still the same.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: claim a permalink and all sublinks in plugin I've built some wp plugins so have some experience but definitely not an expert. I want to build a plugin that can claim a permalink and all sublinks of that permalink and return it to the plugin.
For instance, say I have a website: https://example.com. I want my plugin to add a permalink of /link/ and all it's sublinks - ie, a wildcard of some sort so any sublink is passed to the plugin. So any of the below links will be redirected to the plugin:
*
*https://example.com/link/
*https://example.com/link/test1
*https://example.com/link/testing/another/link/test/here
*https://example.com/link/page.php
*https://example.com/link/some/parameters?var=230&code=abc123
...and the plugin will then determine what data is relevant to output and return the relevant html.
Please can someone help me with this part? Is there a built in function to claim a permalink
and sublinks in this way, and if not, how can this be done? I've been going through the WP functions reference for developers but without knowing what to look for it's a bit of a needle in a haystack.
Even a broad overview or some pointers to the right functions I need to use would be really helpful at this point.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting error when accessing Customizer Page i get this error when i try to access my multisite customizer page.I tried to see what it was, i thought it was a plugin conflict, but i think its something else, i guess
Fatal error: Uncaught Exception: Expected single stylesheet key. in
/var/www/wordpress/wp-includes/customize/class-wp-customize-custom-css-setting.php:71
Stack trace: #0 /var/www/wordpress/wp-includes/class-wp-customize-manager.php(5725):
WP_Customize_Custom_CSS_Setting->__construct(Object(WP_Customize_Manager),
'custom_css[BC_M...', Array) #1 /var/www/wordpress/wp-includes/class-wp-
hook.php(308): WP_Customize_Manager->register_controls(Object(WP_Customize_Manager))
#2 /var/www/wordpress/wp-includes/class-wp-hook.php(332): WP_Hook-
>apply_filters(NULL, Array) #3 /var/www/wordpress/wp-includes/plugin.php(517):
WP_Hook->do_action(Array) #4 /var/www/wordpress/wp-includes/class-wp-customize-
manager.php(934): do_action('customize_regis...', Object(WP_Customize_Manager)) #5
/var/www/wordpress/wp-includes/class-wp-hook.php(308): WP_Customize_Manager-
>wp_loaded('') #6 /var/www/wordpress/wp-includes/class-wp-hook.php(332): WP_Hook-
>apply_filters(NULL, Array) #7 /var/www/wordpress/wp-includes/plugin.php(517):
WP_Hook->do_action(Arra in /var/www/wordpress/wp-includes/customize/class-wp-
customize-custom-css-setting.php on line 71
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Auto updating JavaScript dependancy in functions.php I'm enqueuing scripts with dependency in functions.php file like:
wp_enqueue_script('ads', get_template_directory_uri() . '/js/ads.js', array( ), '1.6', true);
wp_enqueue_script('banners', get_template_directory_uri() . '/js/banners.js', array( 'ads-REKLAMY' ), $timestamp = filemtime( plugin_dir_path( __FILE__ ) . '/js/banners.js' ), true);
banners.js is a script which uses imported arrays from ads.js. I need to update ads.js file automatically whenever I make changes there.
For now I use version parameter like "1.6". So I need to manually change it to, for example, "1.7" and change import line in banners.js file.
Of course banners.js updates automatically with timestamp. Is there a way to do that with dependancy file as well?
And do I do that with import in file using dependency? Basically I need ads.js, the dependency file with exported arrays, to update automatically whenever I make changes there. Any solution will do except Webpack.
A: If I understood your question correctly, you have two JavaScript files: ads.js and banner.js.
You want the site to load the updated version of both of these files, whenever any of these files are changed.
If this understanding is correct, then you may do the following:
function my_custom_theme_scripts() {
$ads_version = filemtime( get_stylesheet_directory() . '/js/ads.js' );
$banners_version = filemtime( get_stylesheet_directory() . '/js/banners.js' );
wp_enqueue_script(
'ads',
get_stylesheet_directory_uri() . '/js/ads.js',
array(),
$ads_version,
true
);
wp_enqueue_script(
'banners',
get_stylesheet_directory_uri() . '/js/banners.js',
array( 'ads' ),
$banners_version,
true
);
}
add_action( 'wp_enqueue_scripts', 'my_custom_theme_scripts' );
This way, whenever any of the files are changed, only the updated versions will be loaded in the frontend. When ads.js is changed, but banners.js is unchanged, the same old banners.js will still get the new ads.js, because the new ads.js will be loaded by the $ads_version timestamp. There's no need to change the dependency handle.
Note: I've used get_stylesheet_directory_uri() and get_stylesheet_directory for consistency (for the currently active theme).
Mixing up get_template_directory_uri() and plugin_dir_path() will work in theory, but that sort of inconsistency may break your code in future. plugin_dir_path() is supposed to be used with plugins, and get_template_directory_uri() for the parent theme.
Also, I've added:
add_action( 'wp_enqueue_scripts', 'my_custom_theme_scripts' );
Just in case you are missing the wp_enqueue_scripts action hook. The code will not work properly without it.
Of course, if you are already using the action hook properly, like:
add_action( 'wp_enqueue_scripts', '<function-that-enqueues-scripts>' );
then please don't add it again.
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Wordpress REST API won't allow me to filter by author ID when called internally, works externally in Postman I'm currently making a custom API endpoint for a site that I'm building, which works absolutely fine aside from this issue with author ID's.
If I do a GET request to website.local/wp-json/wp/v2/podcasts it returns valid JSON of all of the podcasts Custom Post Type. If I do a GET request to website.local/wp-json/wp/v2/podcasts?author=1 it also returns valid JSON of all of the podcasts Custom Post Type - no problems here.
The problem however comes from some other code that I'm writing, I'm trying to do this in a custom function:
$server = rest_get_server();
$podcastsRequest = new WP_REST_Request( 'GET', '/wp/v2/podcasts?author=1');
$podcastsResponse = rest_do_request( $podcastsRequest );
$podcastsData = $server->response_to_data( $podcastsResponse, false );
When I run it in Postman I get the following response:
{
"code": "rest_no_route",
"message": "No route was found matching the URL and request method.",
"data": {
"status": 404
}
}
If I do this call internally inside the function, it works fine:
$server = rest_get_server();
$podcastsRequest = new WP_REST_Request( 'GET', '/wp/v2/podcasts');
$podcastsResponse = rest_do_request( $podcastsRequest );
$podcastsData = $server->response_to_data( $podcastsResponse, false );
I cannot work out why it's producing that error when a direct call to it works fine?
EDIT:
To give more context, this is the function I'm using:
function get_all_posts(WP_REST_Request $request){
$server = rest_get_server();
if($request->get_param('id')){
// $author = $request->get_param('author');
$podcastsRequest = new WP_REST_Request( 'GET', '/wp/v2/podcasts?author=1');
// $articlesRequest = new WP_REST_Request( 'GET', '/wp/v2/articles?author=1');
// $webinarsRequest = new WP_REST_Request( 'GET', '/wp/v2/webinars?author=1');
// $expertInterviewsRequest = new WP_REST_Request( 'GET', '/wp/v2/expert-interviews?author=1');
// $guidesRequest = new WP_REST_Request( 'GET', '/wp/v2/guides?author=1');
} else {
$podcastsRequest = new WP_REST_Request( 'GET', '/wp/v2/podcasts' );
$articlesRequest = new WP_REST_Request( 'GET', '/wp/v2/articles' );
$webinarsRequest = new WP_REST_Request( 'GET', '/wp/v2/webinars' );
$expertInterviewsRequest = new WP_REST_Request( 'GET', '/wp/v2/expert-interviews' );
$guidesRequest = new WP_REST_Request( 'GET', '/wp/v2/guides' );
}
$podcastsResponse = rest_do_request( $podcastsRequest );
$podcastsData = $server->response_to_data( $podcastsResponse, false );
$articlesResponse = rest_do_request( $articlesRequest );
$articlesData = $server->response_to_data( $articlesResponse, false );
$webinarsResponse = rest_do_request( $webinarsRequest );
$webinarsData = $server->response_to_data( $webinarsResponse, false );
$expertInterviewsResponse = rest_do_request( $expertInterviewsRequest );
$expertInterviewsData = $server->response_to_data( $expertInterviewsResponse, false );
$guidesResponse = rest_do_request( $guidesRequest );
$guidesData = $server->response_to_data( $guidesResponse, false );
$merged = array_merge(
$podcastsData,
$articlesData,
$webinarsData,
$expertInterviewsData,
$guidesData,
);
return $merged;
}
add_action('rest_api_init', function () {
register_rest_route( 'wp/v2', '/all-posts', [
'methods' => 'GET',
'callback' => 'get_all_posts',
]);
});
As I've said above, if I just use the new WP_REST_Request( 'GET', '/wp/v2/podcasts' ); endpoints, it works fine, but if I try and use new WP_REST_Request( 'GET', '/wp/v2/podcasts?author=1' ); it returns that error, despite a direct call to website.local/wp-json/wp/v2/podcasts?author=1 returning all the posts for the author.
A: My approach to this was wrong, and I didn't understand the error properly. After taking another look at this, I was able to fix it by replacing this code:
if($request->get_param('id')){
// $author = $request->get_param('author');
$podcastsRequest = new WP_REST_Request( 'GET', '/wp/v2/podcasts?author=1');
$articlesRequest = new WP_REST_Request( 'GET', '/wp/v2/articles?author=1');
$webinarsRequest = new WP_REST_Request( 'GET', '/wp/v2/webinars?author=1');
$expertInterviewsRequest = new WP_REST_Request( 'GET', '/wp/v2/expert-interviews?author=1');
$guidesRequest = new WP_REST_Request( 'GET', '/wp/v2/guides?author=1');
} else {
$podcastsRequest = new WP_REST_Request( 'GET', '/wp/v2/podcasts?author=1' );
$articlesRequest = new WP_REST_Request( 'GET', '/wp/v2/articles?author=1' );
$webinarsRequest = new WP_REST_Request( 'GET', '/wp/v2/webinars?author=1' );
$expertInterviewsRequest = new WP_REST_Request( 'GET', '/wp/v2/expert-interviews?author=1' );
$guidesRequest = new WP_REST_Request( 'GET', '/wp/v2/guides?author=1' );
}
with this code:
if($request->get_param('author')){
$author = $request->get_param('author');
$podcastsRequest = new WP_REST_Request( 'GET', '/wp/v2/podcasts');
$podcastsRequest->set_query_params( array( 'author' => $author ));
$articlesRequest = new WP_REST_Request( 'GET', '/wp/v2/articles');
$articlesRequest->set_query_params( array( 'author' => $author ));
$webinarsRequest = new WP_REST_Request( 'GET', '/wp/v2/webinars');
$webinarsRequest->set_query_params( array( 'author' => $author ));
$expertInterviewsRequest = new WP_REST_Request( 'GET', '/wp/v2/expert-interviews');
$expertInterviewsRequest->set_query_params( array( 'author' => $author ));
$guidesRequest = new WP_REST_Request( 'GET', '/wp/v2/guides');
$guidesRequest->set_query_params( array( 'author' => $author ));
} else {
$podcastsRequest = new WP_REST_Request( 'GET', '/wp/v2/podcasts');
$articlesRequest = new WP_REST_Request( 'GET', '/wp/v2/articles');
$webinarsRequest = new WP_REST_Request( 'GET', '/wp/v2/webinars');
$expertInterviewsRequest = new WP_REST_Request( 'GET', '/wp/v2/expert-interviews');
$guidesRequest = new WP_REST_Request( 'GET', '/wp/v2/guides');
}
This now works as the API endpoint isn't directly set up to match additional parameters on itself, however passing them through with set_query_params() did the job!
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Run a function only once when logging into dashboard I want the Pro version of my plugin to do a version check once when an Administrator logs into the dashboard.
At the moment I am connecting to my API using wp_remote_get() in the main plugin file, but it is being triggered every time the dashboard reloads, for each site that has the plugin installed. That's a lot of unnecessary connections :P
There must be a way to "only run this function once per administrator login session", but I can't find anything about it.
What would be the best way to do this?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to switch out music file for another using php echo this is the current code and audio. I would like to change for a different song, how do I do that?
<source src="<?php echo get_stylesheet_directory_uri(); ?>/thousandyears-fade.mp3" type="audio/mp3">
<!--<source src="<?php echo get_stylesheet_directory_uri(); ?>/thousandyears.ogg" type="audio/ogg">-->
A: you can't change file name. If you want to change file name dynamically try using acf for that.
https://www.advancedcustomfields.com/resources/page-link/
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Display first image's caption I'd like to display the first image uploaded to a post plus its caption.
The code below (functions.php + single.php) displays the image, but I have been able to figure out how to display the caption.
Maybe there are simpler ways of doing this than my code.
NOTE! Image and caption are displayed only if there is an image and if there is a caption.
Code in functions.php
function main_image() {
$files = get_children('post_parent='.get_the_ID().'&post_type=attachment
&post_mime_type=image&order=desc');
if($files) :
$keys = array_reverse(array_keys($files));
$j=0;
$num = $keys[$j];
$image=wp_get_attachment_image($num, 'large', true);
$imagepieces = explode('"', $image);
$imagepath = $imagepieces[1];
$main=wp_get_attachment_url($num);
$template=get_template_directory();
$the_title=get_the_title();
print "<img src='$main' alt='$the_title' class='frame' /><br><br>";
endif;
}
- - - - - - - - - - - -
Code in single.php
<!-- Image 1 -->
<?php if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) {
echo main_image();
} ?>
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I add a zip code service availability checker in Wordpress without Woocommerce? The website is for a business that only provides services in certain zip codes. I would like to be able to display different messages based on if the zip code matches one in my list or not.
I couldn't find any plugins that do this that do not require WooCommerce.
A: This is much simpler version of your question:
Given a list of strings, how do I check the user input is in that list?
You don't need a special service or fancy software to do that, just make a big list of the zipcodes you support and use in_array.
const $supported_zipcodes = [
'zipcode1...',
'zipcode2...',
... etc
];
function ncblender_check_zipcode( string $zipcode ) : bool {
// clean up the zip code, remove trailing spaces and make it all lowercase
$zipcode = trim( strtolower( $zipcode ) );
// don't do empty zipcodes
if ( empty( $zipcode ) ) {
return false;
}
// if our cleaned up zipcode is in the list, return true
return in_array( $zipcode, $supported_zipcodes, false )
}
Now you can create a generic form with a text input, and use that function to check if it's a supported zipcode or not. You might want to find better zipcode validation code online as what I put above is a simple/crude check, but that might just be enough for you
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't create tags or categories I can't create categories or tags from the category page nor creating them from a very new post.
I get the message "unable to add the term to the data base"
Things I've tried:
*
*Checking the database connection through the wp-config.php (correct)
*Deactivating all plugins
*Changing the theme
*Deleting Cache
Nothing seems to work... help?
| {
"language": "en",
"url": "https://wordpress.stackexchange.com/questions/413810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.