INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
What argument does my function need to echo get_results() query results
This is my database query:
global $wpdb;
$table_name = $wpdb->prefix . 'qs_css';
$db_css = $wpdb->get_results(
"
SELECT qs_the_css
FROM $table_name
WHERE qs_css_id = 1
"
);
echo $db_css[0]->qs_the_css; // works just fine
However, I need the query results inside my function:
add_action( 'wp_head', 'quick_qs_db_css', 100 );
function quick_qs_db_css( ) { ?>
<style type="text/css" id="db-css">
<?php echo $db_css[0]->qs_the_css; //outputs null ?>
</style>
<?php }
What arguments does the `quick_qs_db_css()` function need ? Is it possible to pass query results to a function?
Any input would be very much appreciated ! Thanking in advance :) | Why don't you just do..
add_action( 'wp_head', 'quick_qs_db_css', 100 );
function quick_qs_db_css() { ?>
global $wpdb;
$table_name = $wpdb->prefix . 'qs_css';
$db_css = $wpdb->get_results(
"
SELECT qs_the_css
FROM $table_name
WHERE qs_css_id = 1
"
);
<style type="text/css" id="db-css">
<?php echo $db_css[0]->qs_the_css; //outputs null ?>
</style>
<?php }
Seeing as you are using it everytime head is loaded, it would make more sense than to keep the two separate unless there's good reason for it? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, functions, wpdb, sql"
} |
WordPress rewrite does not work for some reason
I am learning how to use WordPress rewrites. As a start i am just trying to redirect any request for " **validate_data.php** " to " **validate-data** ". Here is what i have added to the functions.php file:
function custom_rewrite_basic() {
add_rewrite_rule( 'validate_data.php', 'validate-data', 'top' );
}
add_action( 'init', 'custom_rewrite_basic' );
I know i can execute this in the .htaccess file, but i am testing it here as i have a more advanced case, so it is just a start. What happens when i access "validate_data.php" is that it causes 404 error. I hope someone can tell me what i am doing wrong here? | I am new to WordPress rewrites, so after some StackExchange reading i have figured it out. All rewrites should be passed to index.php, then i can call the page that i want to redirect to, like this:
function custom_rewrite_basic() {
add_rewrite_rule( 'validate_data.php', 'index.php?pagename=validate-data', 'top' );
}
add_action( 'init', 'custom_rewrite_basic' );
In addition i wanted to pass some POST data from the old page to the new page, so i did it like this:
function custom_rewrite_basic() {
add_rewrite_rule( '^validate_data.php(.+)/?$', 'index.php?pagename=validate-data', 'top' );
}
add_action( 'init', 'custom_rewrite_basic' );
Hope that helps new starters like me some day :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "rewrite rules, mod rewrite"
} |
Unable to get Post Category Name and URL
I am very new to wordpress development, please help me out in getting post's category name and its url.
I have tried get_the_category() function but it didn't helped me. Following it the code snippet:
<div class="post-meta-categories"><i class="fa fa-tags"></i> <?php get_the_category(); >
</div> | To understand why `get_the_category();` didn't work we have to take a closer look at the Codex page for that function. More specifically, what that function returns.
> (array) Array of WP_Term objects, one for each category assigned to the post.
You tried to print an Array to HTML, which is why it didn't work.
Instead, take a look at the `get_the_category_list()` function as seen on the Codex, which says:
> Retrieve category list in either HTML list or custom format.
You also forgot to end your php snippet with a `?>`. So to wrap it all up...
<div class="post-meta-categories"><i class="fa fa-tags"></i> <?php echo get_the_category_list(','); ?></div>
Which returns a list of comma separated post categories with clickable links. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, posts, categories"
} |
Is there a resolution limit in image resize?
I am trying to resize an image with width around 6000 to 7000 pixels, but the file size is low (less than 3.8Mb). When I pass such huge images to image_resize function its not resized. Any ideas on this? Wp version 3.5. | Operations on images are more restricted by the required and available memory than by the file size. The bigger the image is, the more memory it will require in order for it to be manipulated (to be manipulated the relevant libraries usually create a bit map image in the memory so your image will take width*height bytes of memory). | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "images"
} |
force https except one page/post
I've spent many hours trying to get this to work; I've read endless posts and tried hundreds of combinations. I'm using a KVM vps so I can edit the apache config files directly if needed.
All I want to do is force https across my whole site (Easy) and exclude one page/post needs to be
I assume it's Wordpress's own permalink rewrite thats tripping me up some how.
Thanks! | I just used this in the functions file in the end
function force_ssl()
{
// Specify ID of page to be viewed on SSL connection
if (is_page(8616) && !is_ssl () )
{
header('HTTP/1.1 301 Moved Permanently');
header("Location: . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]);
exit();
}
// All other pages must not be https
else if (!is_page(8616) && is_ssl() )
{
header('Location: . $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
exit();
}
}
add_action('template_redirect', 'force_ssl'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "single, https"
} |
TinyMCE removes iframe attributes width and height
I'm trying to paste a youtube iframe in to the TinyMCE Editor. Now it always removes the `width` and `height` attributes when switching from TEXT to visual. Now this is ok if values are empty, but if values exist I might need them..
I've tried with the following code in functions.php
function tinyMCEoptions($options) {
$options['extended_valid_elements'] = 'iframe[*]';
return $options;
}
add_filter('tiny_mce_before_init', 'tinyMCEoptions');
Which does work for all attributes but not for width and height. I've also tried
$options['extended_valid_elements'] = 'iframe[width|height|*]';
but it doesn't work. See here:
 {
$options = '*[*]';
$initArray['valid_elements'] = $options;
$initArray['extended_valid_elements'] = $options;
return $initArray;
}
add_filter('tiny_mce_before_init', 'tinyMCEoptions'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "tinymce"
} |
How can I remove this sidebar from my Search Results page?
I don't want to display this particular sidebar on my website's search results page because it displays details (SITE ADMIN, Wordpress.org, etc) which I want to hide from the user.
How can I hide or remove it. Open to all suggestions. I would be very appreciative of your help.
.
But what is your goal exactly? What do you want to not be seen and by who and why? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, metabox, search, sidebar"
} |
Adding an IF Function to Current Custom Category If has Child
I want to add an if statment, this code echos the child categories for the current category, but I only want it to show IF the child categories are true.
Any help would be great - thank you.
<?php (
$terms = get_terms([
'taxonomy' => get_queried_object()->taxonomy,
'parent' => get_queried_object_id(),
]));
echo '<div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;">
<div class="breaker-small">Refine Search</div>';
foreach ( $terms as $term) {
echo '<p class="filters"><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></p>';
}
echo '</div>
<br />';
?> | If you asking about `$terms` has child then only go for it. With this you can try below code as solution:
<?php (
$terms = get_terms([
'taxonomy' => get_queried_object()->taxonomy,
'parent' => get_queried_object_id(),
'hide_empty' => false
]));
// get_terms will return false if taxonomy does not exist or term wasn't found.
// term has children
if($terms){
echo '<div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;">
<div class="breaker-small">Refine Search</div>';
foreach ( $terms as $term) {
echo '<p class="filters"><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></p>';
}
echo '</div><br />';
}
?>
I hope my this code work for you! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
Can I include a custom PHP function in a Wordpress function?
I'm trying to add a shortcode in my Wordpress functions.php file. I want the short code contents to be sent to a PHP function from another part of the website. This is the code:
function short_api($atts){
include (__DIR__.'/api/short_look_up.php');
$api_info = get_api_info($atts);
return $api_info;
}
add_shortcode('apii', 'short_api');
(The get_api_info() is a function in short_look_up.php) Is this the proper way to do this? Right now I'm getting an error and I'm not sure if it is because my include path is messed up, or if Wordpress isn't going to let me do this.
I would also like to know if this is 'bad form' in Wordpress. | Well, yea you kinda can do that. But it's bad practice and it's strongly discouraged. Cause when you call parent function the nested function is being called automatically. So basically the nested function is being called twice. Better and safest way to do it like-
// Include the file or write the nested function outside of the parent function
include (__DIR__.'/api/short_look_up.php');
function short_api($atts){
$api_info = get_api_info($atts);
return $api_info;
}
add_shortcode('apii', 'short_api'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, shortcode, include"
} |
Translation Function missing text-domain
> **WARNING** : Found a translation function that is missing a text-domain. Function `esc_attr_x`, with the arguments 'Search for:', 'label'
I'm Getting this error on a theme I bought. Not sure what the mistake on this is. On the `searchform.php` file I have:
< input type="search" class="search-field" placeholder="Search" value="
< ?php echo get_search_query() ? >" name="s" title=" < ?php echo esc_attr_x( 'Search for:', 'label' ) ? >" / >
I tried removing the spaces in the 'Search for:' area but didn't change the error I was getting. Thanks in advance. | From WordPress Codex (Link):
<?php $translated_text = esc_attr_x( $text, $context, $domain ) ?>
The `$domain` is optional. That´s the reason it´s a warning. Do you have debug set to true? If you want to fix it you have to add the text-domain.
esc_attr_x( 'Search for:', 'label', 'TEXT-DOMAIN-FROM-THEME' )
You can find the text-domain in other translatable strings like this one.
General: It´s better to contact the theme-developer in this case. You paid money - you can expect that it does not have any errors or warnings. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, errors"
} |
How can I use a specific wordpress page template if certain words are used in page title
I'm creating a wordpress theme for a client to use in his existent wordpress site. Anyways, I've completed the theme except one specific thing. I see that he has lots of pages with the keyword Module in the title. Example of the title would be "How to create this product: Module 1." In his previous theme, they had a wordpress page template - page-module.php use specifically for these pages. However, I created a wp page template in my theme with the same name but when I go to any of these pages, it is displaying the default page.php template instead of the page-module.php template. When I switch back to his theme, it work fine with his page-module.php template but when I switch by to my theme, it doesn't work. Can someone please help me understand why it's not working with my theme? | You can adjust the template to use in the fly based on the type of page you're viewing. <
add_filter( 'template_include', 'portfolio_page_template', 99 );
function portfolio_page_template( $template ) {
if ( is_page( 'portfolio' ) ) {
$new_template = locate_template( array( 'portfolio-page-template.php' ) );
if ( '' != $new_template ) {
return $new_template ;
}
}
return $template;
}
You could use that in conjunction with < to check out information about the page requested, like the title.
This assumes you didn't just set your page template on the page itself.
 is wrong
I put my timezone in **America/Lima** ( Setting > General )
But **current_time('timestamp')** show other datetime.
For example: Now in Lima it is 2015-10-25 12:01:00 but current_time('timestamp') says : 2016-10-24 19:01:05
Something am I doing wrong?
PD: My variables in wp_option are: **gmt_offset** is empty, **timezone_string** is America/Lima
Regards | Try passing in a second parameter to tell it to use the GMT offset.
current_time( 'timestamp', true ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "timestamp"
} |
How to get current category
Hello I'm in a bit of a trouble. I don't know what's wrong with what I'm doing. I want to add class to current category. So my php looks like this:
<menu id="nav">
<ul>
<?php $cat_id = get_cat_ID();
foreach( $categories as $c ):?>
<li class="<?php if(($c->term_id) == $cat_id){echo 'active' ;} ?>">
<a href="<?php echo get_category_link( $c->term_id ); ?>" title="<?php echo $c->cat_name ;?>">
<?php echo $c->cat_name ;?>
</a>
</li>
<?php endforeach; ?>
</ul>
</menu>
I just want to add active class to the current category. But this is not working. | You can use `get_queried_object()`, which will return category object.
See documentation:
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, categories"
} |
How to get user meta value in wordpress
I have created a custom usermeta field named "designation" and fetched all its meta value in loop but it shows duplicates and empty values. I have tried to resolve by using array_unique() function but it does not work. Please guide me how can remove duplicates and blank values.
$args = array(
'role' => 'subscriber',
'meta_key' => 'user_designation'
);
// The Query
$design = array_unique($args);
$user_query = new WP_User_Query($design);
// User Loop
if ( !empty($user_query->results) ) {
foreach ( $user_query->results as $user ) {
?>
<option><?php echo get_user_meta($user->ID, 'user_designation', true); ?></option>
<?php
}
}
else {?>
<option value="0">No Category Found</option>
<?php } ?> | You can store the user meta in a variable and check if the variable is empty or not, like below-
$args = array(
'role' => 'subscriber',
'meta_key' => 'user_designation'
);
// The Query
$user_query = new WP_User_Query($args);
// User Loop
$u_meta_array = array();
if ( !empty($user_query->results) ) {
foreach ( $user_query->results as $user ) {
$u_meta = get_user_meta($user->ID, 'user_designation', true);
if (!empty($u_meta)){
$u_meta_array[] = $u_meta;
}
}
$u_meta_array_unique = array_unique($u_meta_array);
foreach ($u_meta_array_unique as $u ) {
echo '<option>' . $u . '</option>';
}
} else { ?>
<option value="0">No Category Found</option>
<?php } ?>
Hope that thing is gonna work. Please let me know if it works or not. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "user meta, users"
} |
WP Add Media Button - Can I set the default size to Original/Full Size
So when I am adding pictures to a blog post [directly to the 'main content area', below the text], they have the 'Medium' Size.... so I have to go to every single picture and change it to Full Size .... is there a way to set Full Size as default.... so that I just need to hit Add Media and all the pictures would display in Full Size?
Cheers, Peter | WordPress will remember the last size you used - just make sure to insert a large media once, and then it will be selected by default for every subsequent item. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads, media"
} |
How to display profile fields with no data in BuddyPress profile view?
It seems like BuddyPress hides profile fields without data in profile view. How can I change this functionality? So that all fields gets displayed, even if they haven't been filled up? | Create a template overload of this file: `buddypress\bp-templates\bp-legacy\buddypress\members\single\profile\profile-loop.php`
Then find this code:
<?php if ( bp_field_has_data() ) : ?>
<tr<?php bp_field_css_class(); ?>>
<td class="label"><?php bp_the_profile_field_name(); ?></td>
<td class="data"><?php bp_the_profile_field_value(); ?></td>
</tr>
<?php endif; ?>
And change it to:
<tr<?php bp_field_css_class(); ?>>
<td class="label"><?php bp_the_profile_field_name(); ?></td>
<td class="data"><?php bp_the_profile_field_value(); ?></td>
</tr>
**EDIT** : We need to force the fetching of empty fields...
So also find this:
<?php if ( bp_has_profile() ) : ?>
And change to this:
<?php $args = array( 'hide_empty_fields' => false, 'hide_empty_groups' => false ); ?>
<?php if ( bp_has_profile( $args ) ) : ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "buddypress"
} |
Hooking dynamic/variable named hook in all cases
There are numerous dynamically named hooks in WordPress such as `get_transient_$transient` where `$transient` is the name of the transient being retrieved.
How do I hook into this so that my filter is called for all values of `$transient`? Something like `get_transient_*` | Unfortunately there is no global transient filter - you'd either need to know all the transient names you want to target, or you'll have to use the special `all` hook (which runs for _all_ actions and filters) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "hooks"
} |
Change name of custom post type archive
I have a custom post type `acme_reviews`. I've namespaced it as suggested in tutorials to prevent future conflicts. But I want its archive page to simply be `acme.com/reviews`, not `acme.com/acme_reviews`. How do I achieve this? This is my code:
function create_reviews_post_type() {
register_post_type('acme_reviews', array(
'labels' => array(
'name' => __('Reviews'),
'singular_name' => __('Review')
),
'menu_position' => 5,
'public' => true,
'has_archive' => true,
)
);
}
add_action('init', 'create_reviews_post_type'); | The register_post_type has_archive option also accepts a string. That string will be used for the archives. See the changes in the code below:
function create_reviews_post_type() {
register_post_type('acme_reviews', array(
'labels' => array(
'name' => __('Reviews'),
'singular_name' => __('Review')
),
'menu_position' => 5,
'public' => true,
'has_archive' => 'reviews',
);
}
add_action('init', 'create_reviews_post_type'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom post types, archives, namespace"
} |
Add stylesheet per layout
Could anyone tell me what is the best and most efficient way to add separate style sheet only to one template? Do I have to have separate header and call it there or there is some Wordpress trick? | If you are talking about a page template, then you can do a conditional check with `is_page_template()` and includethe CSS in the header with `wp_enqueue_syle()`. Something like this:
function themename_include_page_specific_css() {
if ( is_page_template( 'template-name.php' ) :
wp_enqueue_style(
'themename_page_specific_css',
get_template_directory_uri() . '/page-specific-style.css'
);
endif;
}
add_action( 'wp_enqueue_scripts', 'themename_include_page_specific_css' );
Keep in mind, that the parameter you pass to `is_page_template()` must be the name of the template including the path relative to the directory of the theme. Meaning that if your template is in `templates` folder you should write it like:
`is_page_template( 'templates/template-name.php' )`
This will also work with other conditional tags like `is_page()`, `is_single()`, and similar. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "templates, css"
} |
Will simple function names in a class structure conflict with other plugins?
I implement a `class` structure in my plugin, for example:
class Ethans_Plugin {
public function __construct() {
add_filter( 'admin_init', array( $this, 'admin' ), 10, 1 );
add_action( 'admin_footer', array( $this, 'footer' ), 10, 1 );
}
public function admin() {
# code here...
}
public function footer() {
# code here...
}
}
When I define functions with generic names such as `admin` or `footer` will this conflict with any other function that have the same names? Or, since they are within a class, these function names will make them unique? | A method name is not callable without an instance of the class, so no, it cannot conflict with the same method names from other classes, because the class names, including the namespace, must be unique.
Btw: Never register callbacks in a constructor. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "php, plugin development"
} |
Get category of a taxonomy for a queries object in a loop
I am trying to get the category name of a custom post type category in my single-[cpt].php file.
Here is the code I am using:
$queried_object = get_queried_object();
$term_name = $queried_object->name;
echo $term_name;
The category is a sub category. This code just displays the name of the parent category, where I need the name of the category. | Not sure in what form you need the term/s, but here's a piece of code that will first get all your posts' terms, then print them out as linked names.
<?php
// Get Post Terms
$taxonomy_slug = "your-taxonomy";
$terms = get_the_terms( $post->ID, $taxonomy_slug );
if ( !empty( $terms ) ) {
foreach ( $terms as $term ) {
$out[] = '<a href="'. get_term_link( $term->slug, $taxonomy_slug ) .'">'. $term->name
. "</a>\n";
}
echo implode(', ', $out );
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, terms"
} |
How can you disable search for non-members on your WordPress website.
I'm making a community social media website using BuddyBoss's Boss theme. I'm also using Buddypress.
Since I want my website to be private, what I want to do is to disable the search function for anyone who isn't logged in to the website.
The titlebar or header of that theme is fixed meaning that search isn't just a widget but an actual part of the titlebar.
Also, can you tell me the best plugin to restrict access to the website to only the logged-in members so that others can't see anything but one single sign-in or register page.
I'm guessing it can also be done by is_logged_in function but I'm unfamiliar with php coding and would very much appreciate it if you help me out.
If it cannot be done without editing files then, here is a link to a few php files like header.php, search.php, etc.
< | You can restrict any area with `is_user_logged_in()` function. For example: If you want to hide search for non-logged-in users then enclose search `DIV` inside this function like this
if(is_user_logged_in()) {
<div class="search">
</div>
}
Search for the `DIV` that contains `Search Box` and apply function as shown above. By this way you can restrict any area for non-logged-in users.
**NOTE** : Since you are new in `PHP`, Don't forget to enclose this function inside php tags (`<?php` `?>`). And also make sure you don't open `<?php` for this function if it already being opened.
And about your Plugin suggestion, Plugin recommendation is off-topic here. We cannot suggest any plugin as per the site rules, So you have to find your desired plugin by yourself. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, search, members"
} |
Shortcode or Template Page
When we have to add some functionality how to determine should I use shortcode or template file?
Ex : I need to add a page to enable front-end post submission.
I can do it creating a template page or using shortcode and add it to a page. How to identify what is best? | Actually it depends. If you're adding the functionality through a custom plugin or any third party solution rather than theme then the shortcode is best, otherwise you can use a template. You also can use template file with plugin, but then the theme and the plugin will be tightly coupled. That's kinda not preferred. But you can still do it.
Remember for shortcode, it's better to clean the output buffer. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode, templates, page template"
} |
Moving a site from a temporary domain to the live domain
So I have been working with Wordpress for almost a year now, almost all of the times i get stuck with the same problem.
When you purchase a hosting you need to give it the domain of the website, now if the domain dont have A record to your host you won't be able to view your website, so you must edit your local hosts file to view it with this domain.
The other option is to work with a sub-domain, which here starts my problem. when you are working with Wordpress it's creating the pages with the Url on the database and than when you finish the website and want to connect to the main domain you need to edit the whole database. (Lets say the wanted domain is xxx.net, and the temp/subdomain is yyy.net)
What are the best ways of moving and connecting the website to the domain after using a sub/temp domain? | So basically you want to change the URL from subdomain to main domain in your DB so that it will work with your main Domain.
What I do is I use search & replace DB script and in this I will enter my subdomain to search and to main domain to replace.
You can download that script from here and keep the PHP file in the server. <
Thanks | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "database"
} |
Stop the "upload file size" error from printing
I am running a woocommerce site on wordpress. I have updated to the latest versions.
I am seeing that on some pages in the shop that there is an error printing on the page:
Trying to upload files larger than 256M is not allowed!
My question is not how to fix it, but what file is generating that error message, and how to stop it printing. The page is loading as a shop page, and nothing is being uploaded, so I do not need to see the error! | It was a plugin the was trying to upload on Woocommerce pages, that was failing. The updated plugin worked.
I am leaving this question as I saw on others had the issue on the wordpress site | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic, errors"
} |
Migrating a live WordPress website to a Local Server: why some elements of the website are missing?
After many many hours (days, actually) trying to migrate a live WordPress website to a local server, I'm finally getting things to work. One really annoying thing was that some elements of the website were missing, and after many more hours I found out that the culprit was some missing `php` in the `<?php` tag. If I add the `php`, the missing element misteriously reappears on the page. The files I edited was php files inside the `/themes` folder.
Is this normal or am I missing something? How to properly resolve this issue? | It turns out that the what I thought to be incomplete tags was actually just the short form of the delimiter (as you can notice, I'm not very familiar with PHP and WordPress).
Instead of editing every single file and appending `php` to every `<?` tag, the solution could not be easier:
Apache > PHP > PHP Settings > short open tag
**Boom**.
_sigh_ | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, migration, localhost"
} |
Adding an IF ELSE to a function
This is my code, but I only want echo the code if the current category has children.
<?php
$terms = get_terms([
'taxonomy' => get_queried_object()->taxonomy,
'parent' => get_queried_object_id(),
]);
echo '<div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;">
<div class="breaker-small">Refine Search</div>';
foreach ($terms as $term) {
echo '<p class="filters"><a href="' . get_term_link($term) . '">' . $term->name . '</a></p>';
}
echo '</div>
<br />';
?>
So, if
$terms = get_terms([
'taxonomy' => get_queried_object()->taxonomy,
'parent' => get_queried_object_id(),
]));
True - then run the echo. | You can write this code like below-
<?php
$element = get_queried_object_id();
if (!empty($element)) {
$terms = get_terms([
'taxonomy' => $element->taxonomy,
'parent' => $element,
]);
echo '<div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;">
<div class="breaker-small">Refine Search</div>';
foreach ($terms as $term) {
echo '<p class="filters"><a href="' . get_term_link($term) . '">' . $term->name . '</a></p>';
}
echo '</div><br />';
} else {
// Do something
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, conditional tags"
} |
Extending custom shortcode to also be called directly from theme PHP pages
I created the following shortcode which works well in returning the featured image of any given post I am on with a size...
function mfeaturedimage( $atts ) {
$a = shortcode_atts( array(
'size' => 'medium',
), $atts );
return the_post_thumbnail("{$a['size']}");
}
add_shortcode( 'feature', 'mfeaturedimage' );
...But how can I evolve this to "also" be called directly from my content-single.php file, (i.e. **feature();** )
To sum it up, I want a single function that is flexible enough to work as a shortcode and also as a function declaration statement, but I'm not sure how to structure it... | I'm not sure I fully understand, but you can call
echo do_shortcode("[feature site='your-choice']");
within the content-single.php file. If that isn't enough, I suppose a function like this could be made:
function feature($size){
echo do_shortcode("[feature size='{$size}']");
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, shortcode"
} |
Menu not show woocommerce product category
I have problem with configure wordpress woocommerce. On this time I write theme for woocommerce but I can't add product category for menu.
On this address We can see "Product Category" Link.
But my menu section view that: , 0, strpos(the_title_rss(), ' —'));` to work on the RSS feed.
What the above code is suppose to do is if a title has `-` in the title, it removes everything after the `-`.
I think the best way to solve my problem is to run `substr` and `strpos` and save the title in a custom field. I'm not a programmer so has anyone been able to accomplish this or point me in the right direction?
Thanks, | `the_title_rss()` outputs its value straight away so it can't be used in a function like that, you would have to use `get_the_title_rss()`
Or alternatively the_title_rss() has a filter we can hook in to and return your shortened title is possible. (You would add this to your functions.php)
function gg_short_title_rss($title)
{
// This can return false, so check there is something
$short_title = substr($title, 0, strpos($title, ' –'));
if ($short_title) {
return $short_title;
}
// Else just return the normal title
return $title;
}
add_filter('the_title_rss', 'gg_short_title_rss', 10, 1); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, custom field, title"
} |
wp_schedule_event run in background or not?
According to codex,
> Schedules a hook which will be executed by the WordPress actions core on a specific interval, specified by you. The action will trigger when someone visits your WordPress site, if the scheduled time has passed.
Assume that I run a function using `wp_schedule_event`. Function need 20-30 seconds to finish their task.
So it will affect to the user or not? I mean if it is run in background like normal cron jobs it is not affect to the user. | It depends. The initial page load trigger should not but performance may degrade as visitors browse your site until the Cron job is finished.
Is the scheduled event you plan on using PHP or DB intensive? How often will it run?
**Here's how it works**
* The scheduled event (aka Cron job) will be initialized once it's due (or past due) by whoever hits your website. So visiting `www.test.com/somepage/` will tell Mr. WP-Cron, "Hey dude, it's time to wake up and run this Cron job".
* If it takes 20-30 seconds to finish and is an intensive DB or PHP task (e.g. lots of DB INSERT or UPDATE statements, or parsing a huge `.xml` file, etc), there's a good chance the site will be slow for _anyone_ during that time. Especially if you're on shared hosting due to shared CPU and memory.
If it's a Cron job you run once a day or week, I wouldn't worry about the performance hit.
Supporting Answer | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp cron, cron"
} |
Printing a variable inside a custom WP_Query
I would like to know how to print a variable inside a custom `WP_Query`.
I have the following code:
<?php
$args = array (
'post_type' => 'post',
'posts_per_page' =>3,
'orderby' => 'date',
'order' => 'DESC',
);
$loop = new WP_Query( $args );
endwhile;
wp_reset_query();
And I have a post type name value stored in a variable called `$post_type_name`.
However, when adding it to my code
<?php
$post_type_name = get_sub_field('post_type_name');
$args = array (
'post_type' => '$post_type_name',
'posts_per_page' =>3,
'orderby' => 'date',
'order' => 'DESC',
);
$loop = new WP_Query( $args );
endwhile;
wp_reset_query();
the code breaks. Any ideas what could be wrong? | Remove the single quotation, use flowing code. hope it will work
'post_type' => $post_type_name, | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query"
} |
Font not loading
I am working on a site and I'm haveing trouble viewing the font that I need for the slider I have incorporated on the front-page.
Here is the site, the arrows on the slider should appear as a font, but my font is not loading. I placed it in the CSS file.
Here is the Demo, < | I wanted more info about this but i can't comment here because i don't have enough reputation, i may have a solution for you.
First, your font `flexslider-icon` works, but your media queries hide it on screen with more than _860px_.
On screens more than _860px_ arrows become transparent and move out of slider. Here it's a simple solution.
**Make always visible:**
_On`flexslider.css` Replace:_
.flex-direction-nav .flex-next {
right: -50px;
text-align: right;
}
.flex-direction-nav .flex-prev {
left: -50px;
}
_with this:_
.flex-direction-nav .flex-next {
right: 10px;
text-align: right;
opacity: 1;
}
.flex-direction-nav .flex-prev {
left: 10px;
opacity: 1;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development"
} |
Is it possible to remove spaces from existing images?
I have changed my WordPress blog theme but now in older posts images are not working. I have used images names with space `:/` and it is not working now in this theme. I can see the name like `something%20icon.png`. Can I fix it somehow? Not manually all image.
Update: I have find out that problem is that old images that are not working are in root/images (new one are in wp-content\upload...). If I tried url of some image, website.com/images/image.jpg it will open main website not an image. There are images in directory. | You can test flowing code
$img_space = 'something icon.png';
$img_without_space = preg_replace('/\s+/', '', $im);
echo $image; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images"
} |
How can I add ".html" to the end of a single URL on a Wordpress website?
The sites url structure is as follows:
www.sitename.com/mypage/page/
I would like only one certain page on the site to resolve as:
www.sitename.com/mypage/page.html
This is so that when I run the link through the Facebook Sharing debugger at:
... the link works correctly. Currently, Facebook appears to strip query string parameters on pages shared that do not resolve as `.html`. | You can do this quickly by creating a rule in .htaccess.
Log in to Wordpress and go to the page you want to link to.
Then click "preview changes".
Look for the preview_id parameter in the url.
And use this id after de index.php?p= in the .htaccess like:
# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^mypage/page.html$ index.php?p=262 [L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END Wordpress | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, facebook, htaccess"
} |
Require user to input code from an array of allowed codes with Gravity Forms
I have a gravity form that I want to, only allow people submit if they enter a specific code from a possible list of 3.
**Example codes**
1. XH6D
2. 8U2A
3. L9D3
If a user enters **XH6D** into the form, the form will successfully submit, otherwise the form will return an error.
Easy to achieve? | Try below code:
add_filter( 'gform_field_validation', 'custom_validation', 10, 4 );
function custom_validation( $result, $value, $form, $field ) {
$arrWhitelist = array('XH6D', '8U2A', 'L9D3');
if ( $result['is_valid'] && !in_array( $value, $arrWhitelist )) {
$result['is_valid'] = false;
$result['message'] = 'Please enter a value less than 10';
}
return $result;
}
Further, You can review validation in more detail from this url | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "validation, plugin gravity forms"
} |
Proper way of establishing custom landing pages in WordPress
Within WordPress 4.6.1, with the TwentySixteen theme, I have 2 general questions in regards to establishing a landing page.
* From within my child theme folder, where and how do we create a new page to be the new landing page of our site? This page will have a custom coded look and feel. Where in wp-admin do we tell WordPress (please select this to be the default landing page). I don't want to replace index.php, I simply want to create landing page templates.
* When using TwentySixteen, I see how easy it is from wp-admin to set a "Page" to be the default landing page of the site. And I see it comes with "Default Template" and "My Custom Template". Where do we edit these two template files? I would like to create my own template file for my "Page" as well. | reference WordPress Codex on Templates
> A quick, safe method for creating a new page template is to make a copy of page.php and give the new file a distinct filename. That way, you start off with the HTML structure of your other pages and you can edit the new file as needed.
>
> To create a global template, write an opening PHP comment at the top of the file that states the template’s name.
>
>
> <?php /* Template Name: Example Template */ ?>
> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, pages, page template"
} |
Working with Gravatars within a localhost development area
Is is possible to add an author photo (gravatar), while developing our WordPress site offline in a /localhost environment? I see that the gravator process is requesting for an online site to be associated to, but my site is still in a development stage offline.
Thanks for any tips | You cannot make gravatars work offline (they completely rely on remote service), but you can get rid of erorrs and slowdown when offline by overriding them. You can use `get_avatar` filter for it.
There is an Airplane Mode plugin for offline WP dev that does this (among other things). You can use that or just check out its implementation. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "author, gravatar"
} |
How to manage heading font options located in the wysiwyg editor for posts and pages
Within WordPress 4.6.1, when I go to edit a post, from the WYSIWYG editor, there is a drop-down option to apply multiple heading formats to the given text.
,
);
$wp_posts = get_posts($args);
if (count($wp_posts)) {
echo "Yes, the current user has 'your_custom_post_type' posts published!";
} else {
echo "No, the current user does not have 'your_custom_post_type' posts published.";
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom post types, author"
} |
How to use underscore.js in WordPress Admin
I am trying to use underscore in my WordPress Admin. This is what I have done: I enqueue a script in the very end of the page, like so:
function load_admin_scripts() {
wp_enqueue_script( "my-admin", get_template_directory_uri() . "/assets/scripts/admin.js", array('jquery', 'wp-util'), null, true );
}
add_action('admin_enqueue_scripts', 'load_admin_scripts');
...then in the script file, I am at the moment only trying this:
console.log( jQuery ); // is defined
console.log( underscore ); // ReferenceError: underscore is not defined(…)
Can anyone point me to the solution for this? | Go to you chrome **JavaScript** console window and write `_.VERSION`. Then press Enter. It will return you the version of the included **Underscore JS**. Also it will make sure that **Underscore JS** is included or enqueued. And **Underscore JS** is include in **WordPress** admin by default. You don't need to enqueue it. Just use it as you use any where else. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp admin, wp enqueue script, underscore"
} |
Count posts with specific term_meta
I have a custom post type that have many taxonomies. In the front end, a user can assign a 'category' (term_meta) value to the taxonomy - hardware or software.
I wanted to be able to count how many term_meta posts there were.
$base_array = array(
'posts_per_page' => -1,
'fields' => 'ids',
'post_type' => 'cpt',
'post_status' => array('publish'),
'date_query' => array(
'before' => 'next Saturday',
'after' => 'last Monday'
)
);
$base = get_posts($base_array);
echo count($base);
This will give me the total count of posts in the week. But I want to count the posts that have the taxonomy with the term_meta 'hardware' or 'software'.
Is that possible? | So, looking at some other code I have, I feel this would be the right way to go about it. I haven't tested it, but I feel it would work in the way I needed it too (no longer need to count the types).
$base_array = array(
'posts_per_page' => -1,
'fields' => 'ids',
'post_type' => 'cpt',
'post_status' => array('publish'),
'date_query' => array(
'before' => 'next Saturday',
'after' => 'last Monday'
)
);
$base = get_posts($base_array);
foreach( $base as $post_id ) {
$term_meta = get_term_meta( post_id, 'tax_term_type', true );
$term_hardware += ($term_meta == 'term_meta_hardware') ? 1 : 0;
$term_software += ($term_meta == 'term_meta_software') ? 1 : 0;
}
echo count( $term_hardware );
echo count( $term_software ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, custom taxonomy, post meta, count"
} |
Woocommerce quick checkout form
I have a site powered by WordPress and using Woocommerce Plugin i want to add a custom quick checkout form on a single product page here is the reference see the image  ) {
$address = array(
'first_name' => $_POST['fullname'],
'email' => $_POST['email'],
'phone' => $_POST['phone'],
'address_1' => $_POST['address'],
'city' => $_POST['city'],
);
$order = wc_create_order();
$order->add_product( get_product( get_the_id() ), $_POST['quantity'] );
$order->set_address( $address, 'billing' );
$order->set_address( $address, 'shipping' );
$order->set_payment_method( 'cod' );
$order->calculate_totals();
}` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "plugins, customization, woocommerce offtopic"
} |
Get 3 row ID's via ARRAY_A
Below query works fine. But how can I **select the 3 results separately** with the **array_number**?
I need to separate the 3 results correct with help from the array_number. But do not know how.
$records = $wpdb->get_results("
SELECT * FROM wp_rdp_participants_answers AS answ
INNER JOIN wp_rdp_game_images AS game ON game.image_id = answ.image_id
WHERE answ.game_id = $i
&& answ.answer_time LIKE '$day%'
AND answ.answer = game.correct_answer
ORDER BY answ.answer_time ASC
LIMIT 3", ARRAY_A);
if(count($records) > 0){
foreach($records as $rec){
echo $rec->user_id.' - '. $rec->answer_time.' - '.$rec->answer.' - '. $rec->correct_answer. '<br>' ;
}
}
**How do I get now array[0] , array[1], array[2] ?** | Errm...
$item_1 = $records[0];
$item_2 = $records[1];
$item_3 = $records[2];
// e.g.
echo $item_2->answer_time; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wpdb, array, select"
} |
How to change bulk post status
I have about 2300+ post in my blog is it possible to change status from publish to draft at a time?
add_action('publish_post', 'check_publish_post', 10, 2);
function check_publish_post ($post_id, $post) {
$query = array(
'ID' => $post_id,
'post_status' => 'draft',
);
wp_update_post( $query, true );
} | Yes, it's possible to loop all publish posts and change their post status to draft.
add_action('admin_init','wpse_244394');
function wpse_244394(){
$args = array('post_type'=> 'post',
'post_status' => 'publish',
'posts_per_page'=>-1
);
$published_posts = get_posts($args);
foreach($published_posts as $post_to_draft){
$query = array(
'ID' => $post_to_draft->ID,
'post_status' => 'draft',
);
wp_update_post( $query, true );
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "posts, wp query"
} |
PHP Mistake - Whats wrong here?
could anybody tell me please whats wrong with this code ? I get an PHP mistake and cant finde the reason why.
What I want to do is, in the author.php if the author.php is shown as the author php of an person that is subscriber, I want to redirect. If an author.php is shown of any other roles, show it.
$curauth = (get_query_var('author_name')) ? get_user_by('slug', get_query_var('author_name')) : get_userdata(get_query_var('author'));
if ( get_user_role($curauth->ID) === 'subscriber' ):
wp_redirect( '
endif; | From the official _code reference_ :
> wp_redirect() does not exit automatically, and should almost always be followed by a call to exit;
So, you need to call **exit** after the redirect:
$curauth = (get_query_var('author_name')) ? get_user_by('slug', get_query_var('author_name')) : get_userdata(get_query_var('author'));
if ( get_user_role($curauth->ID) === 'subscriber' ):
wp_redirect( ' );
exit; //here!
endif; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "redirect, author"
} |
What is wrong with this?
with this script I wanna ask if the pagination for comments has more sites than 0 and if its so, I wanna use a custom title.
But I got an PHP mistake...can anybody please tell me whats wron with that ?
<?php
$page_comment = get_query_var('cpage');
if ($page_comment > 0);?>
test
<?php endif; ?> | The error is in the syntax; there's a semicolon after the if **condition**. Try this:
<?php
$page_comment = get_query_var('cpage');
if ($page_comment > 0): ?>
test
<?php endif; ?>
Alternative PHP syntax:
<?php
$page_comment = get_query_var('cpage');
if ($page_comment > 0){ ?>
test
<?php } ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments, pagination"
} |
Categories and Tags Conflict after Woocommerce Installation
I now have issues with Categories and Tags after I installed WooCommerce. I had a custom Post Type for 'Products' before WooCommerce. After installation, my post type was taken over. All of my products moved into the WooCommerce 'Products' area.
The problem now is that I have two Categories and Tags sections in my admin, which is affecting user searches etc, so I need to keep using my old categories and tags instead.

wp_get_post_terms($post->ID, 'product-tags', array("fields" => "all"));
// WooCommerce Tags (Empty, Do Not Use These)
get_the_terms( $post->ID, 'product_tag' );
Here is what it looks like now in the when Editing Products:
,
);
register_taxonomy( 'product-tags', 'product', $args ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, tags, woocommerce offtopic, terms"
} |
Functions Filter Question
Why doesnt he input "$meinungen" ?
add_filter('wpseo_set_title', 'wpseo_set_title_callback');
$meinungen = Test;
function wpseo_set_title_callback($input) {
if (is_single()) {
return ''. $meinungen . ''. $input . ' '. $input . '';
}
// return default
return $input;
} | this is for Variable scope.
**_A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function_**
**_A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:_**
$meinungen = Test; // is in global scope
function wpseo_set_title_callback($input) {
if (is_single()) {
return ''. $meinungen . ''. $input . ' '. $input . ''; // now $meinungen local variable which you don not assign value.
}
// return default
return $input; }
to call the value just put global with in function
function wpseo_set_title_callback($input) {
if (is_single()) {
global $meinungen;
return ''. $meinungen . ''. $input . ' '. $input . '';
}
// return default
return $input;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, filters"
} |
Capturing arbitrary semantic URL arguments
So,
My articles have this URL structure :
mydomain.com/category/article-name
I'm using ACF to add additional information to my post types. For example, another text field with some related information to my article. Let's call that field `tab-1`.
I don't wan't to show all this extra data immediately on the article page, but I want to have some sort of subpage on my article for that kind of extra data.
For example, this would be url of my sub page that will show only content from my article `tab-1` field:
mydomain.com/category/article-name/tab-1
Is something like this achievable in wordpress? Essentially, I'd just like to capture that extra URL part `/tab-1` in my template file and than base on it's actual value, show appropriate field on the article.
And all that without getting `404` error :D | The thing in WP that hits a passable balance of such functionality to not so painful implementation is rewrite endpoint.
They are structured a little differently from your example (i.e. `/tab/2`) but they are _easy_ to implement and order of magnitude less painful than dealing with Rewrite API usually is. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "page template, advanced custom fields, routing"
} |
Adding JS to one page
What is the best way to add JS script in wordpress and apply it to one page? As I understand, adding it in template is not recommended. My simple JS is:
var allStates = $("svg.us > *");
allStates.on("click", function() {
allStates.removeClass("on");
$(this).addClass("on");
}); | Create a new dir and file dedicated to your javascript. `/js/scripts.js`.
Wrap your entire javascript like this:
( function( $ ) {
var allStates = $("svg.us > *");
allStates.on("click", function() {
allStates.removeClass("on");
$(this).addClass("on");
});
} )( jQuery );
Then in your theme's functions file, put this code. It loads your new js file.
function your_scripts() {
wp_enqueue_script( 'your-script-handle', get_template_directory_uri() . '/js/scripts.js', array( 'jquery' ), '1.0', false );
}
add_action( 'wp_enqueue_scripts', 'your_scripts' );
That way, all your javascript is available on any page and is loaded only once (afterwards, it's in browser cache). Since your function is `on click` it's fine for it to be available on all pages. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery"
} |
Get ACF value in external jQuery document
I'm trying to get the value of an Advanced Custom Fields _select list_ in an external jQuery document, in order to apply some conditions to it.
I looked for an answer and found only solution involving the use of tags inside the page, which I want to avoid. | Your question is not entirely clear, but it looks like you are in need of `wp_localize_script`, which allows you to pass variables from PHP to a script. You would use it like this (example with two fields):
add_action ('wp_enqueue_scripts','wpse244551_add_field');
function wpse244551_add_field () {
$my_field = array ();
$my_field[] = array (field1 => get_field ('field1'));
$my_field[] = array (field2 => get_field ('field2'));
wp_localize_script ('my-script', 'MyFields', $my_field);
}
Now, in the script you have registered with the handle `my-script` you can access the variable with `MyFields.field1` and `MyFields.field2`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "jquery, advanced custom fields, variables"
} |
Styling the_posts_pagination With Font Awesome
I am using the_posts_pagination to create my pagination links on Wordpress, however I would like to replace 'prev' and 'next' with Font Awesome icons. Is this possible?
I am already using Font Awesome elsewhere on the site.
Kind regards James | You can change the text with the funcion for example.
the_posts_pagination( array(
'prev_text' => __( '<i class="fa fa-arrow-left"></i>', 'textdomain' ),
'next_text' => __( '<i class="fa fa-arrow-right"></i>', 'textdomain' ),
) );
Use whatever icons you can, I used `fa-arrow` icons. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "pagination"
} |
How do I include js without register/enqueue?
I have some js which, rather than register and enqueue, I add directly to a page template.
Currently located outside of WP, I use
<script type="text/javascript" src="/apps/js/amplitude/amplitude.js"></script>
If I move it to a `js` folder inside my theme, how do I then include it in a template without hardcoding a root-relative path... can I use something like `get_template_directory_uri`? | Yes, you can use `get_template_directory_uri` to refer to the theme root path.
<script type="text/javascript" src="<?php echo get_template_directory_uri();?>/js/amplitude/amplitude.js"></script>
But prefered way of doing is to use `wp_enqueue_script()`. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "javascript"
} |
Remove h2 Tag in screen_reader_text
How can I remove the `h2` tag used in the screen reader text? I use the following `$args`, but h2 is still in it:
the_comments_pagination( array(
'add_fragment' => '',
'screen_reader_text' => __( '<h3>Test</h3>' )
) ); | There's a couple issues.
1) You're not supposed to put HTML inside most translations strings ( such as this ).
2) The `screen_reader_text` argument does not accept HTML at all, you need to filter the HTML by using the following hook:
`navigation_markup_template` \- Filters the navigation markup template.
/**
* Modify the given HTML
*
* @param String $template - Comment Pagination Template HTML
* @param String $class - Passed HTML Class Attribute
*
* @return String $template - Return Modified HTML
*/
function change_reader_heading( $template, $class ) {
if( ! empty( $class ) && false !== strpos( $class, 'comments-pagination' ) ) {
$template = str_replace( '<h2', '<h3', $template );
}
return $template;
}
add_filter( 'navigation_markup_template', 'change_reader_heading', 10, 2 );
The above searches the `$template` HTML string and replaces all `h2` tags with `h3` tags. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "pagination, wp parse args"
} |
Restrict submitters from wp-admin
Is it possible, if a subscriber wants to enter wp-admin, that the page would be rdirectet to any page I want ?
If yes, please how :) ? | This is possible, drop this code into your theme's `functions.php` file:
add_action( 'init', 'wpse_244614_no_dashboard_for_subscriber' );
function wpse_244614_no_dashboard_for_subscriber() {
$to = '
$is_subscriber = current_user_can( 'subscriber' );
$in_backend = is_admin();
$doing_ajax = defined( 'DOING_AJAX' ) && DOING_AJAX;
if ( $is_subscriber && $in_backend && ! $doing_ajax ) {
wp_redirect( $to );
exit;
}
}
Now whenever a subscriber tries to reach the backend, he will be redirected to Google, you can use the website homepage `home_url()` or whatever you want. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp admin, users"
} |
Are User Levels Still Currently Used?
I've migrated several sites from standalone installs into a Multisite install.
For the user table, I just recreated each new user individually one by one, and readjusted the user ID's accordingly elsewhere.
Upon investigating the user meta table, it seems that WordPress is creating keys for User Levels.
As mentioned in the Codex, it notes that User Levels were deprecated as of `WordPress 3.0`.
Why is it, that with a fresh installation of WordPress Multsite 4+, adding users, still creates "user_level" meta keys with values of such deprecated user level system?
Are user levels STILL used ANYWHERE in WordPress? or am I safe to simply just ignore those key/value pairs under the user meta table? | Many plugins (and themes) use user levels, you shouldn't use them in yours. They are still used in WordPress probably to offer backward compatibility with the huge number of plugins and themes that use them.
WPCS will throw a warning whenever it busts user levels in code. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "users, user roles, user meta, capabilities, permissions"
} |
Apply custom css for user role
How can I apply custom CSS for user role, both for dashboard and frontend? For dashboard I set:
if( current_user_can('seller', 'partner')) {
function admin_style() {
wp_enqueue_style('admin-styles', get_template_directory_uri().'/admin.css');
}
add_action('admin_enqueue_scripts', 'admin_style');
}
else {
}
how to modify the code to load also on front? btw, Is `if( current_user_can('seller', 'partner'))` correct for checking is user role is `seller` and `partner`? | To enqueue CSS in WordPress you can use:
* `wp_enqueue_scripts` action for the frontend
* `login_scripts` action for the login page
* `admin_scripts`action for the admin side, as you already know
To check user's roles you should get the user object and check the roles property. `current_user_can()` is function intended to check capabilities, not roles.
So, to add CSS based on user roles in the frontend:
add_action( 'enqueue_scripts', 'cyb_enqueue_styles' );
function cyb_enqueue_styles() {
$user = wp_get_current_user();
if( ! empty( $user ) && count( array_intersect( [ "seller", "partner" ], (array) $user->roles ) ) ) {
wp_enqueue_style( 'my-style', get_template_directory_uri().'/some-style.css' );
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, admin css"
} |
Output checkbox per user and save in plugin options
I am looking for a way to save my list of checkboxes as an array within the settings_fields of the plugin. I currently have:
<?php
$WPusers = get_users( 'orderby=nicename&role=administrator' );
foreach ( $WPusers as $user ) { ?>
<input type="checkbox" name="<?php echo $this->plugin_name; ?>[users]" id="<?php echo $this->plugin_name; ?>-users" value="<?php echo $user->ID; ?>" <?php checked( $user->ID, $options['users'], false ); ?> />
<label for="<?php echo $this->plugin_name; ?>[users<?php echo $user->ID; ?>]"><?php echo $user->display_name; ?></label>
<?php } ?>
The only thing is that it only saves one option instead of an array of all the checked boxes. I would love to see a way to store all the checked users within one option of the plugin.
Since I am new to WP development and PHP in general this is all quite new for me. | Change the `[user]` to `[users][]`. Hope that will fix the problem. Now you'll get all the value in associative array within `[users]['your-checkbox-data-array']` So your code will be like-
<?php
$WPusers = get_users( 'orderby=nicename&role=administrator' );
foreach ( $WPusers as $user ) { ?>
<input type="checkbox" name="<?php echo $this->plugin_name; ?>[users][]" id="<?php echo $this->plugin_name; ?>-users" value="<?php echo $user->ID; ?>" <?php checked( $user->ID, $options['users'], false ); ?> />
<label for="<?php echo $this->plugin_name; ?>[users<?php echo $user->ID; ?>]"><?php echo $user->display_name; ?></label>
<?php } ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users, array, plugin options"
} |
Press This for Page
I'm new to WP and like to understand is there possible to make browser bookmarklet _Press This_ for _Pages_ for `wordpress.com`?
If not - probably it's possible for server hosted version, but what should done - do I need to change page template page.php for interaction? | The `press_this_save_post` filter can be used to change the post type from `post` to page. Add the following code to your theme's functions.php or a plugin:
add_filter( 'press_this_save_post', 'wpse244633_press_this_save_post' );
/**
* Filter the post data of a Press This post before saving/updating.
*
* @param array $post_data The post data.
* @return array
*/
function wpse244633_press_this_save_post( $post_data ) {
$post_data['post_type'] = 'page';
return $post_data;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, javascript"
} |
How do I technically prove that WordPress is secure?
One of my clients forces me to do their project without WordPress. But WordPress is the best for his requirements.
What he said is, WordPress is unsecure because WordPress is open source and everyone knows the code. So hacking chance is higher than with a custom website. That is the only thing he does not like about WordPress.
How do I prove that WordPress is secure even code is open for everyone? | Tell your client to read up on cybersecurity, because his premise is nonsense. Security through obscurity has been discredited since 1851 (yes, that's one and a half century ago). The opposite is also untrue. Open source software is not more secure than proprietary software.
The crucial thing in code security is not whether it's open or not, but whether it's well maintained. WordPress has an active community that is constantly alert on security matters. Follow the guidelines. Ask yourself how alert the authors of a rival cms are.
That said, security is a constant threat. There are no proofs or guarantees. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 7,
"tags": "security"
} |
Different text on different sites in a multisite setup
I have a multisite setup with say two websites and both of them use the same theme.
Now, I want to use the same theme for both of the websites but **want to change texts** in few places. say the "read more" button in website1 should show "show more" for website2.
What solution I have thought of:
Duplicating the theme. And then change the texts in the duplicated version and activate that for my second theme.
I guess that will work. But I thought to ask this question to know if there is a better way to do it with a plugin or some code to detect which site I am on.
Since using a duplicate theme, I might have to repeat myself when I do some design changes. | You can create a child theme of that theme and do the modifications. This way you don't need to repeat everything. Just do the modification in the child theme and it will work as the parent theme with your modifications. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, multisite"
} |
Check if plugin exists/active "class_exists()" does not work on plugin territory
I have a simple if statement:
if (class_exists('Woocommerce')) {
echo 'yes';
} else {
echo 'no';
}
This works fine when using it in a theme file (functions.php for example). But when I'm using it on a plugin (plugins/myplugin/myplugin.php) it doesn't work at all. How can I check if the plugin exists/is-active within my plugin to enable/disable some features? Am I missing something? | Woo Commerce provides code to check to see if WooCommerce is installed :
/**
* Check if WooCommerce is active
**/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
// Put your plugin code here
}
If no idea where WooCommerece install then :
$all_plugins = get_plugins();
$active_plugins = get_option( "active_plugins" );
foreach ( $all_plugins as $plugin_path => $value ) {
if( basename( $plugin_path, ".php" ) == 'woocommerce') {
if( in_array( $plugin_path, $active_plugins ) ) {
return true;
}else {
return false;
}
}
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "plugins, plugin development"
} |
How to add LTR to a custom theme which in RTL by default
Regularly we have themes in English that supports RTL, but my case is vice versa. So imagine we have a custom theme that developed in Hebrew, so it's Right To Left. Now I want to know how can I adding LTR support to this theme ?
The use case is having a multi language website using WPML plugin. Just adding a ltr.css to the theme and add proper styles will do the works ?
Any help is appreciated. | I created a `ltr.css` file and put that on theme's root folder. When checked the site in English, the ltr.css loads automatically. So as it seems Wordpress do all needed things in the background and there's no need to do in addition. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "translation, multi language"
} |
Adding simple (one button) Audio player using Custom Fields?
Could you please help me finding a way to adding a simple audio player to my posts using Custom Fields. The player will only have Play functionality and nothing more needed.
The use case is in some Learning website which publish new vocabularies and each vocabulary should have Pronunciation. The final result would be something like this image ` in your template to bind it to the player. Then on the frontend you can bind a click handler to your button that plays the pre-defined audio element.
### The custom field (named audioURL in this example)
`
### In your template file
<audio id="audioPlayer" src="<?php get_post_meta(get_the_ID(), 'audioURL', true); ?>" preload="auto">
### The JavaScript
// Vanilla JS
document.getElementById('yourButtonID').onclick = function() {
document.getElementById('audioPlayer').play();
}
// Or if you're using jQuery
$('#yourButtonID').on('click', function() {
$('#audioPlayer')[0].play();
})
Hope this helps! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, audio"
} |
Creating posts from API data, how to identify posts already imported?
As the title says, I'm using an API to fetch some data which is used to create CPT posts, and need to identify items returned from the API which have already been inserted as posts.
The API returns unique IDs for each item, which naturally leads me toward just making use of the GUID column, but I've read, in no uncertain terms, to never make use of the GUID.
If touching the GUID is taboo, is there an accepted standard practice for doing this? Preferably without adding tables/columns to the database? | Never use GUIDs in WordPress, you definitely got that right.
However nothing prevents you use _concept_ of unique identifiers. You already have values for them, just ignore native column and store them in post meta as arbitrary data. On import you can check for that.
For crazy volume it might require some performance tweaking but generally it holds up. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "api, wp insert post, guids"
} |
Pluigin Migration - I need to move a single plugin to a different website
I need to move a single plugin to a different site. It seems the plugin is custom made and is attached to a database. How do I find all the proper files and move it to the new location successfully? Is there a plugin that can do this or would I have to create a row in the database and manually copy and move the files via FTP? | Plugin file, if created properly, will create it's own db entries for settings etc if needed. You should just move the directory of the plugin from your wp_content/plugins/ directory from one installation to the new one.
You could also zip the plugin's directory (either by ssh, cpanel, or download via ftp and then zip on your computer) and then in the new install of wordpress dashboard go to the plugins/add-new and upload the zip.
If you're looking to export the post entries that have been created by the plugin you can either pull directly from post meta (search for post-type that the plugin created) or use an import/export tool, there are plenty of those plugins on wordpress repository. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, plugin recommendation"
} |
Add Alt attribute to image served with php
I am new to the forum and I hope to provide value..
Question that I have is that I am trying to add alt to a logo using php...
The website is wordpress and is pretty much customized by a different developer..
The php in questions is as follows:
<div class="bd-layoutcolumn-20 bd-column" ><div class="bd-vertical-align-wrapper">
<img class="bd-imagelink-3 bd-imagestyles " src="<?php echo theme_get_image_path
('images/b56392d722ada5890c6d2f29f1dbde4a_logo.jpg'); ?>">
Where would I insert the alt"" in that string?
Thanks in advance!
Mike | just add it in...
<div class="bd-layoutcolumn-20 bd-column" ><div class="bd-vertical-align-wrapper">
<img alt ="my alt tag" class="bd-imagelink-3 bd-imagestyles " src="<?php echo theme_get_image_path
('images/b56392d722ada5890c6d2f29f1dbde4a_logo.jpg'); ?>">
if you're going to make it dynamic you'll need to add the php. Something like this if you're in a loop:
<div class="bd-layoutcolumn-20 bd-column" ><div class="bd-vertical-align-wrapper">
<img alt ="<?php echo get_the_title();?>" class="bd-imagelink-3 bd-imagestyles " src="<?php echo theme_get_image_path
('images/b56392d722ada5890c6d2f29f1dbde4a_logo.jpg'); ?>"> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, tags, html"
} |
Get posts for last working week in WP_Query
With the date_query in wordpress I was trying to get posts for the last working week (Monday to Friday)
I was using:
$base_array = array(
'posts_per_page' => -1,
'fields' => 'ids',
'post_type' => 'cpt',
'post_status' => array('publish'),
'date_query' => array(
'before' => 'next Saturday',
'after' => 'last Monday'
)
);
$base = get_posts($base_array);
But today, a Thursday, returns these values:
> From 31/10/2016 to 28/10/2016
Which makes sense with the 'last' days but is there any way that I can get the last Monday to last Friday? Regardless on the day the WP_Query is queried. | Well, try the below code-
$base_array = array(
'posts_per_page' => -1,
'fields' => 'ids',
'post_type' => 'cpt',
'post_status' => array('publish'),
'date_query' => array(
'after' => strtotime( 'previous week Monday' ),
'before' => strtotime( 'previous week Friday' )
)
);
$base = get_posts($base_array);
I've not tested it. But I tested that below code returns the perfect date-
date('Y-m-d',strtotime('previous week Monday'));
date('Y-m-d',strtotime('previous week Friday'));
It returns-
> 2016-10-24 and 2016-10-28 | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp query, loop, get posts, date query"
} |
Do something with thumbnail image on post publish
For example get width and height of the image and save it to a custom field. | Actually Wordpress offer a good hook , You can get data from Post Published , for more you can follow this example : < Example of a simple update of custom field:
/* Do something with the data entered */
add_action( 'save_post', 'myplugin_save_postdata' );
/* When the post is saved, saves our custom data */
function myplugin_save_postdata( $post_id ) {
// First we need to check if the current user is authorised to do this action.
if ( 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) )
return;
}
else {
if ( ! current_user_can( 'edit_post', $post_id ) )
return;
}
$mydata = 'something'; // Do something with $mydata
update_post_meta( $post_id, '_my_meta_value_key', $mydata );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, custom field, metabox, post thumbnails, publish"
} |
How to validate field when create post
I have a custom CPT and I need that my user fill all the required fields.
How can I check if the field is set and show a message error if is not set?
I have a custom hook to the save_post action that check if is my CPT, there is any action for show error box and prevent create post? | You can check post data in $_POST array on save_post_{custom_post_type_name} action hook.
And if data is not appropriate or according to server side validation and redirect page with custom error args using wp_redirect and , you can grab the errors and display admin notices using admin_notice. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, errors"
} |
Wordpress post visible only those with a link
I posted this question here because it is regarding security. I wanted to know is there any way to WordPress post be only visible when someone has a link. And not to be shown in search or recent posts. I am asking this because i own english-only website and I wish to post something in my language and share link within my country so that other english visitors do not be confused with article on Serbian language.
Regards | Real solution to my question is to install UCE (Ultimate Category Excluder) which allows me to exclude post for showing in front page, feeds, archives, and search results. I can choose where I want it to show, if I do.
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "privacy"
} |
problem with loading pages
I am working on the site the problem I am getting all the pages are not loading except default page. In Visual Composer showing all pages fine, but in browsers doesn't work except homepage default, the message is showing
> The page isn’t working site redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS
I have all the plugins working plus the visual composer I have 4.12 version.
Anyone help please? Appreciate it! | It is impossible to guess what is breaking your site without hands on debug.
In general to debug redirect issues I always recommend Better HTTP Redirects plugin, which has debug mode to stop redirects in process and help figure out which code is generating them. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages"
} |
How to add custom css to login and admin?
I have custom CSS for the login and admin pages.
Is it OK to add it as I've done below, or is there a better alternative?
function custom_admin_css() {
wp_enqueue_style( 'custom_admin_css', get_template_directory_uri() . '/css/admin.css', array(), filemtime( get_template_directory() . '/css/admin.css' ) );
}
add_action( 'login_enqueue_scripts', 'custom_admin_css', 10 );
add_action( 'admin_enqueue_scripts', 'custom_admin_css', 10 ); | That's pretty fine and it's the proper way to add CSS to login page. But you can also change login page CSS by below code-
function the_dramatist_custom_login_css() {
echo '<style type="text/css"> //Write your css here </style>';
}
add_action('login_head', 'the_dramatist_custom_login_css');
This actually prints CSS code inline in the login page. And for admin CSS your way is correct. | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 7,
"tags": "admin css"
} |
Display post image with fancybox
I am trying to display the image with fancybox, but the code shows an empty href which is causing me problems with fancybox.
What is wrong in this kind of code? it's showing up the correct image url, but not where I put it. I would like the src to be in href too.
This is my php code
echo "<a class='fancybox' rel='group' href='".the_post_thumbnail_url( 'full' )."'>";
and this is my output:
<div class="white-block-media">
<a class="fancybox" rel="group" href="">
<img width="600" height="848" src=" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt=""></a>
</div> | When you echo something, you need to be echoing the variable. You are using the_post_thumbnail_url, which in itself is already an echo statement. You should be using get_the_post_thumbnail_url instead.
echo "<a class='fancybox' rel='group' href='" . get_the_post_thumbnail_url( get_the_ID(), 'full' ) . "'>";
EDIT: Also, missing the $post_id, fixed to include it in the function | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, images"
} |
how can i stop custom fields that have apostrophes from breaking my code
I have this code in my php file that creates a button labeled from a field called speaker_file_label and links to a pdf file based on the url entered in the speker_file_url. The fields are created by ACF
echo do_shortcode( "[av_button label='".get_sub_field('speaker_file_label')."' link='manually,".get_sub_field ('speaker_file_url')."' link_target='_blank' size='medium' position='left' color='theme-color']" ).'<br>';
This works perfectly when someone just enters text. However if they say somehting like "joe's files" (without quotes) Then the shortcode breaks and the label just becomes "click"
How can i make wordpress not interpret that apostrophe as part of code? | you could apply the content filters:
echo do_shortcode( "[av_button label='".apply_filters('the_content',(get_sub_field('speaker_file_label'))."' link='manually,".get_sub_field ('speaker_file_url')."' link_target='_blank' size='medium' position='left' color='theme-color']" ).'<br>';
the above added pp marks `<p></p>`
try this:
echo do_shortcode( "[av_button label='".wptexturize( get_sub_field('speaker_file_label'))."' link='manually,".get_sub_field ('speaker_file_url')."' link_target='_blank' size='medium' position='left' color='theme-color']" ).'<br>'; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom field"
} |
Saved emails at dashboard
I want to know if it's possible to send an email through a form in the website and then we can check that email in the normal email service (like gmail, etc) and the wordpress' dashboard.
Thanks | Yes. You can use Contact Form 7 plugin to create a form that will send messages to your email (like gmail, etc) and use another plugin from the same author, Flamingo, to have those messages saved in WordPress database and available in the dashboard.
If you prefer to avoid plugins, here's what you need:
1. Register non-public custom post type `message` to store submissions
2. Create custom html for your form (probably with js validation)
3. Intercept form submission on `init` hook
4. Validate and secure input
5. Create new post of `message` post type with `wp_insert_post()`
6. Send email with `wp_mail()`
7. Output results below the form (validation errors or success message)
As you see, plenty of work/code. If you're a developer, you should go this way to tailor it exactly for your needs. If not, I would strongly recommend you to use mentioned plugins (or any good alternatives) to avoid having some troubles with insecure form. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "forms, email, dashboard"
} |
What would be the URL to display the Wordpress image editor with an image from the media library?
I want to be able to call the Media Library image editor from my plugin. From what I can see looking at the console that it is passing a URL like so But I have not been able to make this work. Does anyone know how it would be done? | If the edit link to your image is:
then the link to the _image editor_ for that image is:
The `$_GET['image-editor']` is checked for in the `edit_form_image_editor()` function.
_PS: I first noticed this trick, when testingthis avatar plugin recently (I'm not related to that plugin)_ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "media library"
} |
Format content value from DB outside of WordPress filters
We're using WordPress to maintain data for a site that gets feed into a `JSON` file.
I've noticed that the post content we add to our file is not getting formatted appropriately. So when we feed it to our other website, the post content has no `HTML`, like paragraph tags.
I know that get_the_content runs the content through the WordPress filter to add all the correct `HTML` formatting. However, since we are making direct calls to the database in a custom script, we're just getting the raw post content.
What would we need to do in order to run our content through the WordPress content filter while our script is not connected to WordPress? | There are a few filters and actions here that run. You'd need to look at the code and figure out what/how to utilize these.
* <
* <
* <
* <
* <
* < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, shortcode, the content, post content, wp autop"
} |
WP Mail isn't sending user account messages, does send from plugins
I'm running WP 4.6.1 and can't seem to send out any user account related emails. Specifically, notify user their account is created (the option is checked when creating accounts in the admin) and password reset emails don't send. No errors, just nothing shows in the receiver email account or spam. Email addresses are verified spelled correctly.
Interestingly, Gravity Forms and WooCommerce emails seem to be sent through fine (marked as spam, but at least they go through). The email notifying the administrator a new account has been created also does arrive.
I'm not using any SMTP or other email plugins at the moment, just WordPresses default mailer. The domain name is not on any blacklists, according to mxtoolbox.com.
Is there a hook or option I've overlooked that disables these emails? Any other ideas?
Thanks! | No, hooks have nothing to do here, all the emails you mentioned (WordPress Gravity Forms and WooCommerce) use the same function `wp_mail`.
I strongly believe this is blocked outside of WordPress, and I suggest you use a SMTP server with a real email address, you can use Postman SMTP Mailer/Email Log which will also help troubleshot emails related problems. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "email, user registration, wp mail"
} |
Exclude custom post type from search conflict with get_posts
I want to hide my custom post type from search results. So, I followed the codex and used:
`exclude_from_search => 'true'` while registering my custom post type.
That hides the custom post type and it does not appear in search results any more.
But now I am unable to load posts using `get_posts` but they appear fine with `WP_Query`. I wonder why it is happening. | `get_posts()` uses `WP_Query`, so you are probably providing wrong arguments, it's worth mentioning that the function has some default arguments.
This should get all posts of the CPT `myCPT`:
$args = array(
'posts_per_page' => -1,
'post_type' => 'myCPT',
'post_status' => 'any',
);
$posts_array = get_posts( $args ); ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development"
} |
Conditionally loading JavaScript based on the Advanced Custom Fields in the post
I am building a site/theme where post content is authored in a modular way (mostly, but not exclusively) with ACF's flexible content field. These fields could have JavaScript functionality attached to them on the public front-end. You might have an image upload that has parallax applied to it or a text block that has a click or hover animation applied to it, for example. I'm trying to determine the most useful method for conditionally loading the different JavaScript libraries that might power this functionality (in the post, as the public sees it, I'm not talking about the admin side). Specifically I'm trying to avoid always loading everything, instead I'm hoping to load specific libraries based on the fields actually present in the post. Is there an established way, outside of the brute force method of looping through the content multiple times to first check for fields and then later to display them? | ACF has finegrained filters for fields when they get loaded.
add_action( 'wp_enqueue_scripts', 'register_my_scripts', 5 );
function register_my_scripts() {
wp_register_script( 'my-script', 'path-to/my-script.js', array(), 'version', true );
}
add_filter('acf/load_field/name=my_field_name', 'load_field_my_field_name');
function load_field_my_field_name( $field ) {
wp_enqueue_script( 'my-script' );
return $field;
}
Normally all scripts should be enqueued in `wp_enqueue_scripts` hook. So you should make sure your script and its dependencies (which haven't been loaded yet) can be loaded in footer. Like this your script gets enqueued when the fields are accessed in the content. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "php, theme development, javascript, advanced custom fields, performance"
} |
Creating custom pages for new users automatically
I am new here and I have a few questions about Wordpress functionality or functionality that I can add through plugins.
Here is what I am trying to accomplish:
1. When a new user signs up, a new page is automatically created, with the page name being the person's user name
2. I would like to beable to add custom sign up fields, and call to it on their new page. For example "Favorite food"
3. On this new page, I would like to make a call to the new field. I would like to show one sentence on the page. For example "My favorite food is potatoes."
I have searched and tried a few plugins, but to no avail. Any suggestions or any tutorials to point me in the right direction would be extremely helpful.
Thank you | You can use `user_register` action for this task. This action fires immediately after a new user is registered.
add_action( 'user_register', 'myplugin_registration_save', 10, 1 );
function myplugin_registration_save( $user_id ) {
//Your Code
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users, signup"
} |
Fatal error: Class 'Requests_Utility_CaseInsensitiveDictionary' not Found in WordPress
While installing the WordPress in the server I am getting below error.
> Fatal error: Class 'Requests_Utility_CaseInsensitiveDictionary' not found in public_html/wp-includes/Requests/Response/Headers.php on line 13
Can any one suggest some solution? | I assume it's a clean installation so I can think of two things:
* The upload (installation) wasn't complete
* Some file permissions are not correct (folders: 755, files: 644)
I'd firstly try to remove all core files and re-upload everything. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "installation, fatal error"
} |
How to have custom post type /example/ and then posts /example/posts.html
I have multiple custom post types and all of them have to have their own "homepage". The url of this homepage is very important and **must be the same with part of the url of the individual posts**. For example:
example.com/custom-post-type/ <- the homepage for this custom post type
example.com/custom-post-type/title-for-a-post/ <- show the page for a post in that custom post.
The issue is that I am getting url conflicts and wp does not run the right templates. I cannot have an empty url for custom-post-type/ so I tried creating a different custom post type and removed the slug. But this is also causing it to render the wrong templates.
Any idea how to approach it? Each custom post type has radically different templates and fields.
Thanks! | This is exactly how wordpress works.
For each Custom Post type Create an archive-custom_post_type_name.php and a single-custom_post_type_name.php
Wordpress automatically loads that file when someone goes to the url.
so if your custom posts types were koolio and notsokool then you would need these 4 files in your theme child (you're using a child theme, right?!)
archive-koolio.php single-koolio.php archive-notsokool.php single-koolio.php
I would take the single file out of your theme folder and copy it to your child them, then add the CPT extension. Do the same for the archive template.
rememeber you'll have to flush the re-write rules if your plugin isn't set to do this by itself...just go to seetings/permalinks and hit save. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, url rewriting"
} |
How to save html and text in the database?
I have two fields. The first is for plain text (but with special characters) and the second for html content (wp_editor is used). Both are later needed for phpmailer.
<textarea style="width:100%;height:200px;" name="doi-altbody"><?php echo $epn_doi_altbody; ?></textarea>
wp_editor( $epn_doi_body, 'doi-body', array( 'editor_height' => '300px' ) );
1) How do i correctly secure them after submitting the form and then save them in the database into a custom table that already exist? (esc_attr, sanitize_text_field ...)
2) And when i want to output the content from the database in the exact and original typed version: How do i make this? (wpautop ...)
I have tried a few things in the last days. But it never worked as i needed. | <textarea style="width:100%;height:200px;" name="doi-altbody"><?php echo $epn_doi_altbody; ?></textarea>
wp_editor( $epn_doi_body, 'doi-body', array( 'editor_height' => '300px' ) );
To get the same result that was saved to the database the output has to be modified.
For the textarea:
wp_specialchars_decode( $epn_doi_altbody, $quote_style = ENT_QUOTES )
For the wp_editor:
wpautop( $epn_doi_body ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "wpdb, wp editor, sanitization"
} |
Why does get_post() not return anything?
Inside my functions.php I use `get_post()` or similar (such as `get_the_title()`) inside some of my functions. It does not return anything. Why? And how to fix that?
P.S: And I can not really add `add_action('somehook', 'myfunc')`, because that makes things display in the wrong place. | When `$post` is null for `get_post` it looks to `$GLOBALS['post']`.
There are several other checks in the source so perhaps you should find out the value of the global variable when you're calling it or give it something besides and empty value.
What does `get_the_id()` return vs. `get_post(get_queried_object_id())`? Or `var_dump(get_queried_object())`?
> `get_post()` \- Retrieves post data given a post ID or post object.
>
> `get_queried_object()` \- Retrieve the currently-queried object. For example:
>
> * if you're on a single post, it will return the post object
> * if you're on a page, it will return the page object
> * if you're on an archive page, it will return the post type object
> * if you're on a category archive, it will return the category object
> * if you're on an author archive, it will return the author object etc.
> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "hooks, actions, post meta, get post"
} |
how to use Data URI for images in WP?
I have a HTMl file that should converted to WP and WooCommerce. In that file, the previous coder used Data URI for `product images` and `banner images` etc. I want to know how should I use data URI with dynamic images which will be uploaded by users ? how should I display that using `the_post_thumbnail` ?
Or even the broader question... Is it wise to use data URI in this context ?
Thanks. | Data URIs don't cache. So you have the same overhead each page request instead of allowing the user to cache those image requests. For product and banner images it doesn't make much sense to take extra processing power to convert them on the fly (each request) or pre-process them which means they'll be stored in the database. It's possible... but I wouldn't say I can recall anyone ever doing it that way with WP. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post thumbnails"
} |
How can I include permalinks in this code?
I use the code below to show site pages and assigned-template.
How do I include the linked-permalink for each page?
<?php
global $wpdb;
$sql = "SELECT post_title, meta_value
FROM $wpdb->posts a
JOIN $wpdb->postmeta b ON a.ID = b.post_id
WHERE a.post_type = 'page'
AND a.post_status = 'publish'
AND b.meta_key = '_wp_page_template'
";
$results = $wpdb->get_results( $sql );
if( !empty( $results ) ) {
echo '<ul>';
foreach ( $results as $result ) {
echo '<li>'. $result->post_title . ': ' . $result->meta_value. '</li>';}
echo '</ul>';
}
?> | You can eventually add ID in $sql, then it will be easier to use get_permalink function in the foreach :
<?php
global $wpdb;
$sql = "SELECT ID, post_title, meta_value
FROM $wpdb->posts a
JOIN $wpdb->postmeta b ON a.ID = b.post_id
WHERE a.post_type = 'page'
AND a.post_status = 'publish'
AND b.meta_key = '_wp_page_template'
ORDER BY a.post_title ASC
";
$results = $wpdb->get_results( $sql );
if( !empty( $results ) ) {
echo '<ul>';
foreach ( $results as $result ) {
echo '<li><a href="'.get_permalink($result->ID).'">'. $result->post_title . ': ' . $result->meta_value. '</a></li>';}
echo '</ul>';
}
?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "permalinks"
} |
How does mediaelement.js work in WordPress?
Is it automatically loaded for newly developed themes? Or should I enqueue it?
I'm developing a theme and video player doesn't seem to be working properly. Should mediaelement.js be included in footer.php or header.php in order to make the [video] shortcode work in template? | WordPress core handles the enqueuing of the MediaElement.js scripts and styles automatically when the `[video]` shortcode is used:
_From`wp_video_shortcode()`..._
/**
* Filters the media library used for the video shortcode.
*
* @since 3.6.0
*
* @param string $library Media library used for the video shortcode.
*/
$library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
if ( 'mediaelement' === $library && did_action( 'init' ) ) {
wp_enqueue_style( 'wp-mediaelement' );
wp_enqueue_script( 'wp-mediaelement' );
}
The code above shows that the MediaElement.js JavaScript is added to the header, since that's how things are handled by `wp_enqueue_script()` by default. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, video player"
} |
Override plugin text domain in child theme
I have a plugin YITH Wishlist in use and I want to override their translation with my own translation which I have included in my child theme.
So basically I created this folder: /mychildtheme/languages
and placed this file in it `yith-woocommerce-wishlist-de_DE.mo` / `yith-woocommerce-wishlist-de_DE.po`.
Within my functions.php I did the following:
add_action( 'plugins_loaded', 'yith_load_textdomain' );
function yith_load_textdomain() {
unload_textdomain( 'yith-woocommerce-wishlist' );
load_plugin_textdomain( 'yith-woocommerce-wishlist', false, get_stylesheet_directory_uri() . '/languages' );
}
But this has no effect. Does somebody knows how I can override a plugin text domain with my custom translations?
Thanks! | If you want to override a plugin text domain, create (if not exist) a folder named `languages` and another one `plugins` (in languages) in the wp-content folder.
This folders is intended, with the template and file hierarchy, to be load upon the other that could exist.
When you update a plugin, text domain that you modified and copied into this folder will not be erase. It's up to you to maintain it up to date. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "plugins, child theme, translation, localization"
} |
Get all data form users and users metakey
please if possible help me, how i can get all users and meta keys via mysql query? i need in page display id, usename, email and metakey (user_work, user_street, user_state) for each users. Please explain me how it possible
Thanks | WordPress provides a function get_users which display all the user detail and which field you want just pass in the 'fields' array.
$users = get_users( array( 'fields' => array( 'ID','user_login', 'user_email') ) );
foreach ( $blogusers as $user ) {
$user_work = get_user_meta( $user->ID, 'user_work', true);
$user_street = get_user_meta( $user->ID, 'user_street', true);
$user_state = get_user_meta( $user->ID, 'user_state', true);
echo 'User ID : '.$user->ID.' Username : '.$user->user_login.' E-Mail : '.$user->user_email.' Work : '.$user_work.' Street'.$user_street.' and Stat is :'.$user_state;
}
Cheers :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "user meta"
} |
Modify RSS - remove image and add text
I'd like to remove the image from my RSS feed and add some "Read more" text. The code I have is
<content:encoded><![CDATA[<?php
echo strip_tags(the_excerpt_rss(), '<p><a>') .
'<a href="' . the_permalink_rss() . '">Read more</a> at ' .
the_permalink_rss();
?>]]></content:encoded>
But when this is run, I still have the image and the extra text is weirdly formatted. eg:
<content:encoded>![CDATA{ <img src="{imgpath}" alt="{imgAlt}"/>{postExcerpt}...{link}{link}<a href="">Read more</a> at]]>
Why does this happen? I followed the instructions at Remove images from get_the_excerpt but it still shows images and the extra text is formatted strangely. | Note that `the_permalink_rss()` and `the_excerpt_rss()` do **echo** the output, **not return** it.
With your current snippet, replace `the_excerpt_rss()` with:
apply_filters( 'the_excerpt_rss', get_the_excerpt() );
and replace `the_permalink_rss()` with:
esc_url( apply_filters( 'the_permalink_rss', get_permalink() ) );
You could also use:
<content:encoded><![CDATA[
<?php the_excerpt_rss(); ?>
<a href="<?php the_permalink_rss(); ?>">
<?php esc_html_e( 'Read more', 'mydomain' );?>
</a>
<?php esc_html_e( 'at', 'mydomain' );?>
<?php the_permalink_rss(); ?>
?>]]></content:encoded>
where you strip the RSS excerpt through the `the_excerpt_rss` filter or use the above approach to get the excerpt output to strip it.
You could also try using `printf` with:
<content:encoded><![CDATA[%s <a href="%s">%s</a> %s %s]]></content:encoded>
etc. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "images, rss, excerpt"
} |
Is there a way to execute a php script outside Wordpress?
I need to create a script to remove some users from a WordPress DB. I would like to be able to remove those users without modify directly the database and just executing the script.
I would like to know if WordPress has a some kind of SDK or something to do this thinks without need to create a plugin.
Is it possible? | A number of ways to do this.
You could use wp-cli, WP REST API or even include `wp-load.php` from a custom script and use built-in `wp_delete_user()` function. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "database, users"
} |
Remove add_menu()'s second argument from it's submenus list
I use `add_menu()`, then I add number of `add_submenu()`.
**CODE**
add_menu_page( 'Config', 'MDW Config', 'manage_options', 'mdw-config', 'config_general_info', '', 45);
add_submenu_page( 'mdw-config', 'General info', 'Info', 'manage_options', 'general-info', 'config_general_info');
add_submenu_page( 'mdw-config', 'Google Analytics Integration', 'Google Analytics', 'manage_options', 'ga-integration', 'config_ga_integration');
And then some more submenus. What it achieves is:
` duplicates, it seems like it's submenu of itself. I'm pretty sure it's possible to avoid it, as for example _Appearance_ menu, which is default one, links directly to it's _Themes_ submenu.
What am I doing wrong? | Try this:
add_menu_page( 'MDW Config', 'MDW Config', 'manage_options', 'mdw-config', 'config_general_info', '', 45);
add_submenu_page( 'mdw-config', 'General info', 'Info', 'manage_options', 'mdw-config', 'config_general_info');
add_submenu_page( 'mdw-config', 'Google Analytics Integration', 'Google Analytics', 'manage_options', 'ga-integration', 'config_ga_integration');
What you have to do is simply overwrite the name of your first submenu page by assigning it to the same `menu-slug` but with different name. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "dashboard"
} |
How to remove "» (title of post or page)"?
Whenever I put a name on a post or page, it will show up in the corner of the website as such: "» (post / page title)". When I checked the code, it looks like this:
<body>
"» (title
" == $0
(...)
How do I remove it? Thanks | Search your code for `»` and narrow down where it's referenced. Chances are not many places. Look in all your theme and plugin folders. Even do a `grep` on the `/wp-content` folder.
`grep -winr ./wp-content -e '»'`
It looks like bad php code -- maybe `copy/paste` where the quotes didn't match up. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, title"
} |
How to make native video player full width?
This is what I have now:  ) {
$content_width = 850; }
The content width on my template is 850px. But setting the content width didn't help.
How to make WordPress native video player width 100%? | I added this to my style.css and now the video player is fully responsive!
.wp-video, video.wp-video-shortcode, .mejs-container, .mejs-overlay.load {
width: 100% !important;
height: 100% !important;
}
.mejs-container {
padding-top: 56.25%;
}
.wp-video, video.wp-video-shortcode {
max-width: 100% !important;
}
video.wp-video-shortcode {
position: relative;
}
.mejs-mediaelement {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.mejs-controls {
display: none;
}
.mejs-overlay-play {
top: 0;
right: 0;
bottom: 0;
left: 0;
width: auto !important;
height: auto !important;
} | stackexchange-wordpress | {
"answer_score": 19,
"question_score": 7,
"tags": "theme development, video player"
} |
Conditional tags don't work
I'm trying to display different templates in archive.php page. I need to load different article display depending on custom post type. Here is my code:
<?php if(is_singular('libri')) :?>
<?php
// WP_Query arguments
$args = array (
'post_type' => 'libri',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
the_title();
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata(); ?>
<?php else : ?>
<?php endif; ?>
<?php get_footer();?>
Anyway the page doesn't display anything. How can I get rid of this problem?
Thanks! | `is_singular` will return false on an archive page. If you wanted to check if you are on an archive for a post type, you would use `is_post_type_archive( 'libri' )` , or you can create an `archive-{post_type}.php` file, which on this case would be `archive-libri.php`
References: < < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, custom post type archives"
} |
Retrieving post meta array (attachment)
I have a post meta for image uploads which allows a maximum of 5 files.
The data is stored in like this:
a:5:{i:0;s:3:"694";i:1;s:3:"694";i:2;s:3:"697";i:3;s:3:"695";i:4;s:3:"696";}
The problem is, I can't get the image URLs. My code:
<?php $ppics = get_post_meta( get_the_ID(), 'shop_demosc', false );
$ppurl = wp_get_attachment_url($ppics);
foreach ($ppics as $key => $ppurl){
echo '<img src="'. print_r($ppurl) .'">';
} ?>
This code returns:
Array
(
[0] => 694
[1] => 694
[2] => 697
[3] => 695
[4] => 696
)
whats wrong? How can I get the URLs to the 5 images? | Your `var_dump` looks like it's returning an array because you're passing `false` to `get_post_meta()`. Also you don't want to `print_r()` on an `echo` line.
> Retrieve post meta field for a post.
>
> * **$post_id** _(int) (Required)_ Post ID.
> * **$key** _(string) (Optional)_ The meta key to retrieve. By default, returns data for all keys. Default value: ''
> * **$single** _(bool) (Optional)_ Whether to return a single value. Default value: false
>
<?php
$ppics = get_post_meta( get_the_ID(), 'shop_demosc', true );
// if the value is an array of an array, just set to the first array
if( is_array($ppics) && count($ppics) === 1 && is_array($ppics[0]) ){
$ppics = $ppics[0];
}
foreach ( $ppics as $key => $attachment_id ) {
$image_url = wp_get_attachment_url( $attachment_id );
printf( '<img src="%s">', $image_url );
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post meta, attachments, images"
} |
Function not working on any file other than the main plugin file
My plugin has several php files that are included on the main plugin file. I am using some functions on the other files but they don't work there. They work when I use them on the main plugin file.
For example,
**On the main plugin file _"test-plugin.php"_**
<?php
/*
Plugin Name: Test Plugin
Description: test
Version: 1.0
*/
include_once( plugin_dir_path( __FILE__ ) . 'test-file.php' );
**On the other file _"test-file.php"_ (same directory with test-plugin.php)**
<?php
function enable_user_registration() {
if(!get_option('users_can_register')) {
update_option( 'users_can_register', '1' );
}
}
register_activation_hook( plugin_dir_path(__FILE__), 'enable_user_registration' );
Regards.. | I guess you should be using `register_activation_hook()` with the full path including filename, not just the path:
register_activation_hook( plugin_dir_path(__FILE__) . 'test-plugin.php', 'enable_user_registration' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, functions, hooks"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.