INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Easiest way to call an External rest API?
I am currently attempting to make a simple GET call on an external API and then to populate the page with the response, no matter I search I cannot seem to find a clear or understandable answer as how to do this or if it is even possible.
Edit:
I have found an answer, however I feel that I should expand on what I wanted as I feel that Mark Kaplun was right. What I wanted to be able to do was make an external API call to GET a response from my own backend service (dreamfactory in this case). The issue that arose, largely due to my unfamiliarity with WordPress, was that I could not find a way to send off an api call. What it transpired the issue was that I attempted to make the api call inside the page and not inside the "Functions.php" page that I should of done, calling a short-code inside the page editor to activate it. | Mark is right, without knowing more, this is a hard question to answer. This is a general guide though (not written by me) that I've used for my projects in the past.
<
It should get you started and then if you have other questions, please let us know. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 1,
"tags": "api"
} |
Which has more impact on site performance? Template overrides or hooks
I'm building a website with the "Neighborhood" Theme and WooCommerce. The site is quite large and is heavily customized and I have to set dozens of divs to not display or edit the text, which I'm using a large translation function for that uses multiple switch statements. As well as hooks for editing multiple woocommerce buttons. So my question is, is it better in regards to performance to hide all of these divs and use the function to edit text and redirections, or should I override multiple template files in woocommerce to make these changes? | The templates are, by definition, the mechanism to define how a certain woocommerce page would look, and child themes are, by definition, the way you change a behavior of a theme beyond what it allows for in the Admin UI.
Overriding the templates in a child theme is the best practice. _(Bear in mind that this means you may have to come back and update the template when Woocommerce updates their templates.)_
Also, changing the content in PHP is usually cheaper than letting the default PHP run then changing the content in the browser, because it duplicates work. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "templates, woocommerce offtopic, hooks, performance"
} |
Custom page template with entirely different design. Is it possible in?
I'm trying to create 2 different page templates for a website here.
The idea is that admin should be able to select this new template for specific pages at the time of creating it. Also, they should be able to select the old design when ever they want.
What could be the best way to design a new page template with entirely new designs instead of changing any current designs? | Short answer is, yes it's possible.
That is the very purpose of having a template hierarchy. Different templates having different functionality and design based on your needs.
For example, you can create a `tag-facebook.php` and make it look like Facebook, while having a `tag-twitter.php` that looks nothing like Facebook, but just like Twitter!
There is one thing you should consider. Most of the page templates have the following structure:
// Header
<?php get_header();?>
// The page's content is here
// Footer
<?php get_footer();?>
If you follow this structure, you can't fully customize your page since `get_header()` and `get_footer()` will always include the same header and footer templates in your page.
Unless, you define different headers and footers to use in different designs. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "pages, templates"
} |
Featured image size in column
I have a featured image preview in column view in my Custom Post Types. Now I want to change the size of it. This is my code:
add_filter('manage_posts_columns', 'add_img_column');
add_filter('manage_posts_custom_column', 'manage_img_column', 10, 2);
function add_img_column($columns) {
$columns['img'] = 'Featured Image';
return $columns;
}
function manage_img_column($column_name, $post_id) {
if( $column_name == 'img' ) {
echo get_the_post_thumbnail($post_id, 'thumbnail');
return true;
}
}
And I see it like this:
 | In functions.php : Make sure featured images are enabled
add_theme_support( 'post-thumbnails' );
then add
add_image_size( 'thumbnail-news', '100', '75', true );
And in the code above change
echo get_the_post_thumbnail($post_id, 'thumbnail');
to
echo get_the_post_thumbnail($post_id, 'thumbnail-news'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, post thumbnails"
} |
Change the CSS of the Customizer API
Heyo,
I want to make the `Customizer` of my `Theme` look a bit different than usual. For example I want to make the `width` to `400px` instead of `300px`. Is there a way I can include custom-CSS for that?
Thanks in advance! | Definitely, you can use the customize_controls_enqueue_scripts hook to load custom CSS and JS.
This is an example of making the panel 400px:
File: **sample-theme/css/customizer-controls.css**
.wp-full-overlay.expanded {
margin-left: 400px;
}
.wp-full-overlay-sidebar {
min-width: 400px;
}
.wp-full-overlay.collapsed .wp-full-overlay-sidebar {
margin-left: -400px;
}
File: **sample-theme/functions.php**
/**
* Enqueue style for customized customizer.
*/
function sample_theme_customize_enqueue() {
wp_enqueue_style( 'custom-customize', get_theme_file_uri( 'css/sample-theme-customizer-controls.css' ) );
}
add_action( 'customize_controls_enqueue_scripts', 'sample_theme_customize_enqueue' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, theme customizer, api"
} |
How to load google font only if custom logo is not uploaded
How can I load Google font only if custom logo is not uploaded?
I know how to load resource if we are on this or that page, but not sure how to do this? | There is a function for this purpose, called `has_custom_logo()`. You can check whether the website has a custom logo or not by having this conditional:
if ( ! has_custom_logo() ) {
// Enqueue some google fonts
wp_enqueue_style( 'google-fonts', ' );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "logo, fonts"
} |
Can I modify a WP_Query instance or clone it with modifications?
Let's say I have created a `all_movies` function that returns a `WP_Query` instance that includes all posts of a custom type `movie`.
$movies = all_movies(); // returns WP_Query instance
I would like to modify the `WP_Query` object to only show a certain author's movies, maybe in code like this:
$movies = all_movies();
$movies->filter(['author' => 14]); // not real code
Or maybe I could create a new `WP_Query` instance that copies the existing instance with modifications:
$movies = all_movies();
$new_movies = $movies->filter(['author' => 14]); // not real code
Of course, I would expect the query to be lazy only resolve at the last minute. I'm used to other ORM systems where something like this is possible. Is it possible with Wordpress' `WP_Query` class? | `WP_Query` can repeatedly _loop_ through the retrieved posts multiple times, but it was never meant to query them repeatedly/iteratively. You can just do `$query->query($args)` again, but there is little point as opposed to just making a new clean object.
In your case I think it would make sens to have your custom function accept optional parameters, along the lines of:
function all_movies( $args = [] ) {
$defaults_args = ['stuff'];
return new WP_Query( array_merge( $default_args, $args ) );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query"
} |
It would be a right way to enqueue the script using foreach loop?
It would be a right way to enqueue the scripts using foreach loop only for `jquery`, `jquery-ui-widge`t, `jquery-UI-accordion`, `jquery-ui-slider`, `jquery-ui-tabs`, `jquery-ui-datepicker`, `Jquery-ui-dialog` and `Jquery-ui-button` because I have to write it many times so
I have make it like this:
$jquery_ui = array(
'jquery',
'jquery-ui-core',
'jquery-ui-widget',
'jquery-ui-accordion',
'jquery-ui-slider',
'jquery-ui-tabs',
'jquery-ui-datepicker',
'jquery-ui-dialog',
'jquery-ui-button',
);
// Framework JS
foreach ($jquery_ui as $ui) {
wp_enqueue_script($ui);
}
So I just want to know this laziness is a right way or not:) | Yes you can. But to make sure the script has not already been registered or enqueued, use `wp_script_is()` as follows:
foreach( $jquery_ui as $ui ) {
if( !wp_script_is( $ui ) ) {
wp_enqueue_script( $ui );
}
}
This will prevent conflicts due to another instance of the script being already enqueued. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "wp enqueue script"
} |
Get more than 10 posts in a specific category with the wordpress api
I'm currently building an Ionic app that uses the Wordpress api. I can retrieve posts in a specific category by using the following:
// Retrieve filtered data for the categories to show posts.
function getCategoryName(categoryName) {
return ($http.get(svampeURL + 'posts?categories=' + categoryName).then(handleSuccess, handleError));
}
The problem is that it only returns 10 as it is some sort of default. I have tried using the per_page=50 argument but it doesn't seem to work. I have also read the documentation of the api and it seems like they don't describe this scenario.
Is there any way to get more than 10 posts in a specific category? How do I change this default return? | See if your url is correct. Example: `website.com/wp-json/wp/v2/posts/?categories=3&per_page=50` | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 2,
"tags": "api, rest api, wp api"
} |
How to get the user meta data for a post?
Im trying to get the user meta data from a post but only getting the one user:
$args = array(
'numberposts' => 10,
'offset' => 0,
'category' => 0,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true
);
$recent_posts = wp_get_recent_posts( $args, ARRAY_A );
foreach ($recent_posts as $post) {
$user_id = get_the_author_meta('ID', true) // is this correct
// Is there a function that I need to pass the post ID ($post["ID"])?
var_dump($user_id);
}
When another user makes a post, I cant get their meta data. How, please? | You can pass the post's author as an argument to `get_the_author_meta`:
get_the_author_meta('ID', $post->post_author);
The second argument is the user's ID. This is stored in the post object in your loop, which you can access it by using `$post->post_author`.
## Reason
The reason behind the current code of yours that isn't working is this piece of code that is included in the `get_the_author_meta()`:
if ( ! $user_id ) {
global $authordata;
$user_id = isset( $authordata->ID ) ? $authordata->ID : 0;
} else {
$authordata = get_userdata( $user_id );
}
If you set the second argument to true ( which is the `$user_id` ), it will trigger the `else`, and by triggering the else you are passing a `true` to the `get_userdata()`, which will obviously won't work.
Take a look at this page of code reference for more details. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, author"
} |
Multisite Installation is all the same site
I have set up my network effectively - but when I go to a subsite dashboard - it is still going to the main site dashboard - I literally changed a whole site and it overwrote my main site. I was able to restore a backup. If I go to the direct URL - I do get the new site - hit dashboard or customize and it goes back to the main site dashboard.
I can't figure out how to change the subsites. Each are their own sites and will be mapped to their own domains, but they are for a single client. | Smells like an .htaccess thing. Have you replaced the contents of .htaccess with the ones provided by WordPress? Also, according to the Codex, you may need to add `Options FollowSymlinks` at the start of the file. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "multisite, installation"
} |
WordPress Multisite with subdomains on different domains
I want to create a WordPress Multisite network with domain mapping. In my project, we need 10 sites in the network. Every site uses a subdoman on differnt domains.
Fo example:
* blog.apple.com
* news.facebook.com
* social.twitter.com
Is there any chance to do that with the multisite feature? I've only found solutions with different subdomains on a single domain. | Did you try to assign the appropriate subdomains using 301 redirections? I think it would be possible if you run all these websites on one server.
1. Create multisite with subdomains in one domain
2. Assign custom subdomains directories to paths of your network installations.
As far as I know, it is pretty simple in CPanel and difficult but possible in DA. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, subdomains, domain mapping, network admin"
} |
How do I run a PHP script from Wordpress environment, like `wp shell`?
`wp shell` is a very useful tool that lets you run PHP statements and expressions interactively, from within a Wordpress environment. It lets you use all the functions, classes and globals that you can use within Wordpress.
Is there a similar tool that will let me run a PHP file? | Yes, there is! I didn't find it at first, but wp cli offers a command called `eval-file` which does what you want:
$ echo '<?php echo is_wp_error("foo") ? 1 : 0;' > example.php
$ wp eval-file example.php
0 | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 9,
"tags": "wp cli"
} |
Is this really always bad? (variables in l10n functions)
I needed to translate strings on another language than the current $locale, so I need to change the locale and restore it later, and I really couldn't repeat all the code for the 30++ strings I had to translate.
So I ended up with this function:
function __2($string, $textdomain, $locale){
global $l10n;
if(isset($l10n[$textdomain])) $backup = $l10n[$textdomain];
load_textdomain($textdomain, get_template_directory() . '/languages/'. $locale . '.mo');
$translation = __($string,$textdomain);
if(isset($bkup)) $l10n[$textdomain] = $backup;
return $translation;
}
Now, as per this famous article, I really shouldn't have coded that function :
<
...But it simply works. So my question is: is it really ALWAYS wrong to pass variabled to l10n functions? An eventually why? And why shouldn't I use my function if it just works? | The answer is: sometimes. As long as you know what you are doing, there are no problems in terms of bugs. There can be situations where this is possible and safe, and other where it can be necessary or extremely useful.
To complete and share the code above, I add the following:
function _e2($string, $textdomain, $locale){
echo __2($string, $textdomain, $locale);
}
// example
_e2('hello','stratboy','it_IT');
**UPDATE:**
Some bonus code can be found here:
How to get a traslated string from a language other than the current one? | stackexchange-wordpress | {
"answer_score": -2,
"question_score": 0,
"tags": "localization, l10n"
} |
Is database safe after merging a branch of a more recent version over an older one?
Use case:
2 git branches:
staging (wp4.7x -- or whatever) production (wp4.7x -- or whatever)
Then I do a wordpress update on staging. Then merge staging files on production.
At this point, I will have all the most updated files on production, but the database wasn't touched. Dangerous? Or maybe wordpress will detect old db and ask to update? | For DB upgrades wordpress compares the db version number it hs in the code to the one in the DB. It makes no difference how the new code got there as long as it is the correct one. Which begs to caution that if you go that way you should put wordpress into maintenance mode before pulling from git (I will admit of not doing that myself, but it is still a risk better avoided). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "database, upgrade"
} |
How to override styles from child theme if all the styles are in a folder?
In my situation, style.css file has just package information and a comment as: All css files are placed in /css/ folder.
In the css folder, I see a bunch of different styles and I don't exactly know which one controls what!
Any suggestions on overriding the CSS rules from a child theme? | As long as your theme has been set up properly for child themes, it doesn't matter how many style sheets there are or where they are located in the actual theme. The style.css in the child theme directory will prevail over them.
If it isn't set up properly you can re-enqueue with a different priority.
If you can't do that, then you can make your css selector more specific (ie, .header h1 instead of just h1) and/or add !important to the value. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "child theme, css"
} |
Automatically generator a Wordpress installation on my subdomain
i am currently working on a project which i hope will result in a e-commerce platform as Shopify. The reason im building this project, are so my customers are able to pay monthly for day Wordpress site.
To the question, how can i make it possible to automatically generate a Wordpress installation, when my customers make an account on my website. I want this installation to be created on generated sub-domain.
Thanks in advanced.
Markus | You'll want to setup a Multis-site network - <
If you know your way around code what you'll need to do is use the wpmu_create_blog() function - < \- to create a blog whenever a user registers.
What I would recommend would be a front-end form so when someone registers they can enter the name of the site they want this way you hook into the form save action to then create the site based on the user. Also doing so this way you can add a security check in place to prevent spam. If on the other hand you create a new blog whenever "anyone" registers this could be exploited fairly easily. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, subdomains, domain, automation"
} |
How to Take Logo Out of Navigation Menu?
So I added my logo to the navigation panel at the top of my site. The theme doesn't support having a logo there... I just added the `<img />` code into the header HTML.
The only way to get the image where I wanted it though was to add it to the "top-navigation" section where all the page headings are contained.
I installed a responsive menu plugin and set it so the top navigation disappears and turns into the three bar icon when the page gets to a certain width (for example on a mobile device).
The problem is that since my site logo code is within the top navigation section the logo also disappears.
So basically I'm looking to take the logo code out of the top navigation section so it will remain when the page shrinks.
I have no idea how to code css or how to integrate the HTML with the css so I don't know how to do this.
My site theme is Fashionistas.
Very appreciative of any help. | I was going to leave this as a comment since questions about CSS are off-topic here, but it wasn't going to fit.
There is a rule in your inline CSS at line 75, which hides the menu of the screens sized less than 750 pixel. This is it:
@media only screen and (max-width: 750px) {
#top-navigation {
display: none !important;
}
}
Which hides both your logo and the menu. To revert this, you can either add your image outside the `#top-navigation`, or hide only the menu, not the whole navigation.
For example, add a simple media query and add it to `Appearance > Customize > Custom CSS`:
@media only screen and (max-width: 750px) {
#top-navigation {
display: block!important
}
#top-navigation .sf-menu {
display: none !important;
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, html, logo"
} |
My header not showing up
I'm starting a brand new theme and my `header.php`'s content is not being output to the browser, the browser is just plainly ignoring it.
Any ideas?
EDIT: I just wasn't calling it by get_header(), sorry! | Simply having a `header.php` in your theme's folder will not output your header to the browser. You have to call the header too.
To call the `header.php` file, you should use `get_header();` at the top of almost every template (Almost!) such as `page.php`, `single.php`, `archive.php` and so on.
Do the same for `footer.php` to get the footer.
I can't quite recall the full list, but these are the main files:
archive.php
author.php
category.php
date.php
front-page.php
home.php
index.php
page.php
single.php
singular.php
search.php
tag.php
taxonomy.php
This also applies to child pages, and child theme's pages, such as `page-abc.php`.
Also, take a look at the WP Hierarchy schematic. This is greatly useful for those who want to start developing themes. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "headers"
} |
Using ACF field in do_shortcode()
I have a shordcode for Contact Form 7 form. I want use Advanced Custom Fields for ID value. How Can I do that?
the ACF with ID value:
the_field('form');
shordcode:
<?php echo do_shortcode( '[contact-form-7 id="29"]' ); ?>
Any solution? :) | Simple as this:
<?php echo do_shortcode( '[contact-form-7 id="'.get_field('form').'"]' ); ?>
You have to notice, you should use `get_field()` to return the value. `the_field()` will echo it. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "shortcode, advanced custom fields"
} |
Line numbering on Wordpress frontend
I've looked at all plugins possible and none have what I need, which is line numbering on front-end only.
Let's say my WordPress post looks like this in the back-end editor:
> My first line
>
> Second line
>
> This is the third
I want my front-end page to look like this
> 01 My first line
>
> 02 Second line
>
> 03 This is the third
Can it be done with code or a plugin? | It's not really a WordPress related question, but it's kind of related to visual editor.
If your content is just raw text separated by `<br>` tags, I can't think of any way to do it. But if your content's structure is like this:
<p>My first line</p>
<p>Second line</p>
<p>This is the third</p>
Then you can use a CSS feature called counter:
body {
counter-reset: section;
}
p::before {
counter-increment: section;
content: "Line number " counter(section) ": ";
}
This will output the following result:
> Line number 1: My first line
>
> Line number 2: Second line
>
> Line number 3: This is the third
Which you can customize it to get your favorite style. It doesn't have to be `p` element, it can be anything. Actually `p` elements are already considered as blocks, and automatically occupy a new line. You can see more examples at W3 Schools. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "visual editor"
} |
Edit the archive-{custom_page}.php via WP editor
Is there any way to edit the archive-{custom_posts}.php page via the WP page editor? I wan't to add some custom text and links... | Maybe if you go to `appearance -> editor` in the dashboard your page can show there. Or you can install this plugin. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "editor"
} |
wp_mail ignores the name in From field
I am trying to set custom From name and email in `wp_mail` headers but somehow, `wp_mail` ignores the name but gets the email correctly.
This is the headers code I am using.
$headers = array(
'Content-Type: text/html; charset=UTF-8',
'From: Michelle Titus <[email protected]>'
);
I am not using such plugins which can alter the data. However, I am using GravityForms which I don't think should conflict with what I have here.
I cannot use the `wp_mail_from_name` and `wp_mail_from_email` because the `wp_mail` is called dynamically with different From data each time. Maybe I can put some conditional logic but I thought I should ask for a better solution.
And there's no question resembling my issue anywhere, as far as I searched Google.
Thanks | Is there an actual `[email protected]` email address? And (more importantly) is the `brazilbr.com` the domain name of your site? If not, then your hosting place will ignore the 'from' email when it processes the `wp_mail(`) command.
You need to make sure that the 'from' email address you use in `wp_mail()` is an email address on the domain for your site. If needed, created an email account on your domain, then use forwarding rules to get it to the [email protected] email address.
You can also set the 'reply-to' in the mail header to whatever you want. But the sender email must match the domain of the site that is sending the mail. If not, the mail will get delivered, but will not have the 'from' address you specified. And, some mail clients might block your email as spam, since the sender email doesn't match the sender domain. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp mail"
} |
How to add array
I have this following code,
if ('plugins.php' === $pagenow ||'update-core.php' === $pagenow ) {
// wp_safe_redirect( home_url() );
// Now check the current user
$user = wp_get_current_user();
if ( $user->user_login == 'Remo' ) {
wp_safe_redirect( admin_url() );
exit();
}
The above code redirects the user named `Remo` to the home page whenever he tries to access the update page in dashboard.
So, now I want to add another user named 'Sam'.
How can I add sam using array.
Thanks in advance :-) | You don't need array to do this. The following code will be worked. You have to just add other username also inside if condition with `or` operation.
if ('plugins.php' === $pagenow ||'update-core.php' === $pagenow ) {
// wp_safe_redirect( home_url() );
// Now check the current user
$user = wp_get_current_user();
if ( $user->user_login == 'Remo' || $user->user_login == 'Sam') {
wp_safe_redirect( admin_url() );
exit();
}
If you want to use array you can add users to array and then you can use `in_array` function to check it.
if ('plugins.php' === $pagenow ||'update-core.php' === $pagenow ) {
// wp_safe_redirect( home_url() );
// Now check the current user
$user = wp_get_current_user();
$users = array("Remo", "Sam");
if ( in_array($user->user_login, $users)) {
wp_safe_redirect( admin_url() );
exit();
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, users, redirect, user roles, wp redirect"
} |
Pass variable from action back to template
I'm new to developing with WordPress. I read here that a good way to process data posted from forms is to insert an action on the init function like so:
add_action( 'init', 'contact_form_send_email' );
My function seems to be processing the data correctly, but I can't figure out how to make a variable available within the same template that has the form.
What is the way to do this? I've heard that setting global variables is not a good way to go. | The difference between `add_action()` and `add_filter()` is semantic not technical, except that a filter expects a returned value and an action does/will not. The question is whether `contact_form_send_email()` **needs** to be called-at /hooked-to `init`.
If not, you can define your filter in the template with `apply_filters()`, and then hook to it to run your function and return a value to it.
In _template page_ :
$some_variable = 'some value';
$some_variable = apply_filters('my_filter_hook', $some_variable);
In _functions.php_
add_filter('my_filter_hook', 'contact_form_send_email', 10, 1 );
function contact_form_send_email( $some_variable ) {
//do stuff
$some_variable = 'some new value';
return $some_variable;
}
* * *
To help determine where you need to hook, this Actions Reference can be useful. Scroll down and you will see some template specific hooks as well. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, templates"
} |
How to add a link to the tax term in the admin Edit page?
I have a custom taxonomy, 'genre.'
I'd like my editors, from the 'Edit Genre' screen (in the admin), to be able to link to the front end page for that genre/term.
So, at the top of the 'Edit Genre' page there would be a link such as:
See this page: mysite.com/genre/fiction
* or - if I could have a 'Preview Changes' button, as in the Post Edit screen.
Possible?
Note, I've seen some solutions that suggest putting in a dummy custom meta box, using the description as the text/link. Is there a way to do the above without doing the meta box? | The dynamic hook `{taxonomy}_term_edit_form_top` can be used to output a link to the term's archive page.
Since we're dealing with terms under the `genre` taxonomy, we will attach our callback to the `genre_term_edit_form_top` hook.
/**
* Adds a link to top of edit term form for terms under the
* genre taxonomy.
*
* @param object $tag Current taxonomy term object.
* @param string $taxonomy Current $taxonomy slug.
*/
add_action( 'genre_term_edit_form_top', 'wpse_add_genre_link', 10, 2 );
function wpse_add_genre_link( $tag, $taxonomy ) {
$term_link = get_term_link( $tag ) ; ?>
<div class="term-link-container">
<strong><?php _e( 'See this page:', 'text-domain' ); ?></strong>
<a href="<?php echo esc_url( $term_link ) ?>"><?php echo esc_html( $term_link ); ?></a>
<div><?php
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "admin, notices"
} |
Including a specific Javascript Script in a template. Is my code correct?
I have a contact form that I would to place within my WordPress theme that pulls in specific Javascript AND CSS Files.
To pull in the Javascript (called x.js) is this correct? I tested it and it seems to work fine, I just want to see whether I've done this correctly!
Also - would I do exactly the same for a .css file?
Here's the php code I placed in the functions file:
add_action('wp_enqueue_scripts','contactform');
function contactform(){
if ( is_page_template('page-contact.php') ) {
wp_enqueue_script('contact-javascript', 'js/x.js');
}
}
Thanks for all help. | you need to give the part to the js/x.js file, the rest is correct. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, javascript"
} |
What's the best way to 'include' a file in WordPress?
Ive built simple web applications in the past using 'include' functions and typically I've used this command:
<?php include($_SERVER["DOCUMENT_ROOT"] . "/data.php"); ?>
This has worked great OUTSIDE of WordPress but my question is - can this be applied to a WordPress Environment?
_(I should add the reason I am doing this: it is because I have to load a file which is approx 2MB into a WordPress Template and it crashes each time I try to save the file)._ | You can include the PHP files in WordPress just the same way you do it anywhere else.
However, WordPress offers more constants and functions for defining a path for the `include()` function.
Instead of using `$_SERVER["DOCUMENT_ROOT"]`, move your PHP file to your theme's folder, and use this to include it:
require_once ( get_template_directory() . "/data.php");
The reason behind moving the file to theme's folder is both for security, and organization. Now, use this in the _very first line_ of your `data.php` file:
if ( ! defined( 'ABSPATH' ) ) die();
This will prevent direct access to your PHP script by entering the URL. `ABSPATH` is a core WordPress constant, and if it's not defined, then it means your script is probably being accessed directly.
Also, to prevent accidental conflicts occurred by including the file multiple times, I would suggest you use `require_once()` instead. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "include"
} |
how to add stylesheet to particular plugin only?
I am developing plugin wherein I want to add `bootstrap.css` to plugin setting page. But if I add css, it will get add to whole WordPress admin panel.
Is there any way to apply css to particular plugin only? | You can use `get_current_screen()` to check which page is being displayed now, and if it was your plugin's page, enqueue the script.
However the easier way is to use the global variable, `$pagenow`:
if(( $pagenow == 'my-plugin.php' ) {
wp_enqueue_style('my-style', 'URL-HERE' );
}
In which `my-plugin.php` is the slug of your plugin screen's URL, such as:
www.example.com/wp-admin/my-plugin.php | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development, admin css"
} |
How I do I host a simple html file through wordpress? (see details)
I want to host a webpage on my main directory so that my url reads:
www.example.com/sample.html
I know I can use FTP service but is there any plugin I can use to accomplish this? | You can use this plugin "File Manager" - < you will need to have the requirements below:
PHP 5.2+ Firefox 12+ Google Chrome / Chromium 19+ Internet Explorer 9+ Opera 12+ Safari 6 Mogrify Utility (Optional) GD / Imagic (Optional) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "ftp"
} |
Query_posts $query_string
I have a query that looks like:
`query_posts($query_string."&post_type=attachment&posts_per_page=9&paged=".$paged);`
I'd like it to looks something like:
$args = array(
'paged' => $paged,
'posts_per_page' => 9,
'post_type' => 'attachment'
);
query_posts($args);
I am trying to integrate `$query_string` into the `query_posts` with `$args`...can anyone point me in the right direction.
Thanks,
Josh | After some searching I found the parameters I needed: < (on Line 231)
//////Search Parameter
//
's' => $s, //(string) - Passes along the query string variable from a search. For example usage see:
'exact' => true, //(bool) - flag to make it only match whole titles/posts - Default value is false. For more information see:
'sentence' => true, //(bool) - flag to make it do a phrase search - Default value is false. For more information see:
I added `'s' => $s` to my `$args` which passes along the query string, which is what I was looking for :-)
My code now looks like:
$args = array(
'paged' => $paged,
'posts_per_page' => 9,
'post_type' => 'attachment',
's' => $s
);
query_posts($args); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "query posts, query string"
} |
How to get short description under heading - Visual Composer
We are looking a Visual Composer Shortcode list. Please look at the image, how to put content below the heading just like "Text2" as similar to Custom Heading .,
"base" => "xxxxx",
"icon" => plugins_url('img/vc-icon.png', __FILE__),
'description' => __( 'xxxxxxxx', 'xxxxxxxxxx' ),
"params" => array(
array(
'type' => 'dropdown',
'heading' => __( 'Select xxxxxx', 'xxxxxxxxxx' ),
'param_name' => 'id',
'admin_label' => true,
'value' => $xxxxcvx
),
),
) );
I implemented `'admin_label' => true,` and then it's working fine.... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, visual editor"
} |
"Display Site Title and Tagline" checkbox not working?
I'm trying to develop a theme. but "Display Site Title and Tagline" checkbox not working nothing change when i check or uncheck the site tile and tagline still exist. also the color option not giving any effect? please help my code for the header text is:
<header class="image-bg-fluid-height" id="startchange" style="background-image: url('<?php echo( get_header_image() ); ?>')" >
<h1 class="h1-hdr"><?php bloginfo('name');?> </h1>
<br/> <br/>
<P id="header-pa"><?php bloginfo('description');?> </P>
<a class="btn btn-primary btn-lg outline " role="button" href="#" id="btn-header">WATCH A VIDEO</a>
<br/> <br/>
</header> | this peace of code will help you
<?php
if (display_header_text()==true){
echo '<h1>'.get_bloginfo( 'name' ) .'</h1>';
echo '<h2>'.get_bloginfo('description').'</h2>';
} else{
//do something
}
?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "theme development, themes, theme customizer"
} |
Adding Filter to Homepage only
I want to execute the following code only on the homepage for the default post loop. I added this to the functions.php, but it doesn't work. It works and adds the according altering classes if I use it without if condition. Not sure what I am missing. Any help appreciated Thx, C
global $current_class;
$current_class = 'flex-container';
function rt_oddeven_post_class ( $classes ) {
global $current_class;
$classes[] = $current_class;
$current_class = ($current_class == 'flex-container') ? 'flex-container-reverse' : 'flex-container';
return $classes;
}
if ( is_home() || is_front_page() ) {
add_filter ( 'post_class' , 'rt_oddeven_post_class' );
} | Even if wrap your filter in a `if` statement, the `function` still will be executed. Try this:
global $current_class;
$current_class = 'flex-container';
function rt_oddeven_post_class ( $classes ) {
if ( is_home() || is_front_page() ) {
global $current_class;
$classes[] = $current_class;
$current_class = ($current_class == 'flex-container') ? 'flex-container-reverse' : 'flex-container';
return $classes;
}
}
add_filter ( 'post_class' , 'rt_oddeven_post_class' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "filters, homepage, post class"
} |
How to check the array of featured images IDs
I'm trying to show some specific text on top of the featured images depending on their IDs. Some of the featured images will have the same text.
$post_thumbnail_id = get_post_thumbnail_id();
if($post_thumbnail_id =='2030') {
echo '<span>Location</span>';
}
How do I check the array of $post_thumbnail_id?
The following example does not work.
if($post_thumbnail_id == array('1000','2000')) | This is solely a PHP question. But as birgire mentioned, you can use `in_array()`. So, change your code to this:
$post_thumbnail_id = get_post_thumbnail_id();
if( in_array( $post_thumbnail_id, array(1, 2, 3 ) ) ) {
echo '<span>Location</span>';
}
The first argument is your value, the second one is the array you want to search in. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "post thumbnails, array, id"
} |
how to display all posts Custom fields dynamically?
<?php
foreach($getPostCustom as $name=>$value) {
echo "<strong>".$name."</strong>"." => ";
foreach($value as $nameAr=>$valueAr) {
echo "<br /> ";
echo $nameAr." => ";
echo var_dump($valueAr);
}
echo "<br /><br />";
}
?>
Actually I created a "Custom Post Type" and for that post type I added Custom Fields and Now I want to Display all my custom field values in the particular post type posts. The above Code displays all Custom Fields. Please help me to retrieve only custom fields of the particular Posts Only. Thanks In Advance.. | <div class="col-xs-12 col-sm-12 col-md-8 col-lg-8 left_column"> <?php
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<h1> <?php the_title();?> </h1> <?php
$post_meta = get_post_meta(get_the_ID());
foreach($post_meta as $key=>$value)
{
echo "<strong>".$key."</strong>"." => ";
foreach($value as $nameAr=>$valueAr)
{
echo "<br /> ";
echo $nameAr." => ".$valueAr;
}
echo "<br >";
}
the_content();
endwhile;
endif; ?>
</div> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, php, custom field"
} |
functions to create term and child terms
I've got a MySQL table with car makes and models. I'm using php to pull the data and enter it into terms in WordPress. What WordPress function would I use to create the term and then the taxonomy `ua-auction-category`. Then the child term for the model.
Example: `Ford -> Fusion`. Hope I was clear enough.
Any questions let me know. | To create a taxonomy, you should use `register_taxonomy()`. This function accepts three arguments:
<?php register_taxonomy( $taxonomy, $object_type, $args ); ?>
The documents on the codex are plenty self explanatory.
Now, to insert a term into a taxonomy, you can use `wp_insert_term()`. Again this function accepts 3 arguments:
<?php wp_insert_term( $term, $taxonomy, $args = array() ); ?>
You can check the codex page for instructions. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "taxonomy, terms"
} |
Wordpress pagination not working with search page
In my search page, My query returns 11 pages with this search: `?q=2&s=chem`
But when I try to access another page other than the first, like `?q=2&s=chem&paged=2` for example, WordPress shows `error not found`.
Note: If I leave empty s variable in URL, I have no problem.
This is my `WP_Query` :
$args = array(
'number' => $number,
'offset' => $paged ? ($paged - 1) * $number : 0,
's' => $_GET['s'],
'meta_query' => array(
'relation' => 'OR',
[
'key' => 'comp_name',
'value' => $_GET['s'],
'compare' => 'LIKE'
]
),);
Someone knows how to fix this problem? | by default, wordpress has it's own main query in search page, in your case you didn't changed the main query, and just create a custom query
paged is a reserved query variable which is used first by your main query, when your main query dosent have same results, you face a 404 error you have 3 choices:
**1\. change paged variable**
you can rename your page variable from paged to page or something else which is not used by wordpress by default
**2\. override 404 page**
function override_404()
{
if ( is_search() && isset($_GET['s'])) {
global $wp_query;
$wp_query->is_404 = false;
}
}
add_action('init', 'override_404');
**3\. override main query ( best )**
function change_search_query() {
if ( is_search() && isset($_GET['s'])) {
$args = array();
query_posts( $args );
}
}
add_action('init', 'change_search_query'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, wp query, search, location search"
} |
Header Sidebar Won't Move Lower - Want to Align with Header Logo
I can't get the search box to go any lower. It seems the padding, margin, etc. are all 0. But, when inspecting, it seems that the box containing the search bar isn't as large as the box containing the header logo is taller, thus sits more flush with the bottom.
How do I go about adjusting the size of the box that the search bar is in so that it will sit flush with the bottom of the section (bottom-aligned with the logo?)
Thanks!
staging.yodega.com
 has no height value, so it's going to adjust. It could be specicifity though. Try this:
.site-header #dokna_product_search-2 {
margin: 40px 0 0 0;
}
You can add !important to the css, but that sometimes adds more confusion in the long run.
Add the code. Let me know if it works, but leave it in so we can confirm it's there. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets, css, html"
} |
How can I use my custom wordpress theme on two websites?
I've built a custom wordpress theme for a website, and now I want to apply the same theme to another site.
I could easily do this by duplicating the website and changing the content, but then subsequent changes to the theme won't be carried over (and I foresee a lot of changes that will need to be made in the future). I need a way to keep the theme synchronised between website.
Ideally, I will be able to change the theme on either site and apply the changes to the other, but if the changes have to be made on one "main" website that's OK too. | You have 3 options:
1. Use multisite, so you have a centralized theme and any number of wordpress sites you want.
2. Submit your theme to the wordpress theme engine, the one it loads all the themes available so any update you push to it, will require an update in both sites with just one button.
3. An script that will copy the theme to both sites (not a good option) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, theme development, themes"
} |
How to move HTML form to WP Theme
:) Hi good people :)
I have a beautiful layout of advanced form in html5. There's some JS scripts and CSS with flex box. What's the easiest way to add this form into WP theme? I try with CF7 but there's some issues, I should rearrange code and CSS specially for CF7 and I want to avoid that... any suggestions?
Thank you all! | use wp_enqueue_script() function to load your required javascript and css files for the form. Then follow this tutorial to have knowledge about creating a form plugin and how to use that.
You have another option left. If you are familiar with WordPress page template then you can create a page template for the page that contains the form. Read more about page template from here. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "forms"
} |
Order by meta value (numeric value lower to higher)
I'm trying to order my custom posts by lower price to the higher price (numeric value). Here is my query to do that. But it's not ordering by lowest to highest price.
<?php
$tours = new WP_Query(array(
'post_type' => 'tour',
'posts_per_page'=> 12,
'meta_key' => 'tour_price',
'orderby' => 'meta_value_num',
'order' => 'DESC'
));
The avobe query only ordering the posts by descending order, not ordering by price. | I think that what you're looking for is this:
<?php
$tours = new WP_Query(array(
'post_type' => 'tour',
'posts_per_page'=> 12,
'meta_key' => 'tour_price',
'orderby' => 'meta_value_num',
'order' => 'ASC'
));
Descending means going down, as in, high to low.
Ascending is going up, low to high. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp query, meta query"
} |
Plugin directory says that my plugin it's not availabe in Spanish, but it is
I uploaded my first plugin to the wordpress repository, it includes the .po and .mo files for Spanish in the languages folder; the Text Domain and Domain Path strings are also specified in the plugin header, and the plugin works fine both in english and spanish when installed. However, when I go to the spanish version of the wordpress plugin directory (at < it says that the plugin it's still not available in Spanish.
I tried uploading the po using the web interface in translate.wordpress.org, but now the translations are in "waiting" state and I'm not sure how to approve them
Maybe I'm missing something, should I add something to the plugin? I can't find enough documentation about this | To be able to approve your own plugin translations you have to post in the Polyglots site:
<
a message like this:
"Hello, I’m the author of the {insert plugin name and a link} plugin. Could you allow me to approve translations in my native language (es_ES), please?"
And select "Editor Request" in the "Post Type" dropdown. Hopefully an editor of the Spanish team will grant you Editor privileges for your translation and you will be able to approve it.
Here you can see an example post:
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development, language, plugin repository"
} |
attach unattached featured images to respective posts
So, somehow after many migrations i ended up with thousands of featured images that are unattached. They exist in the media library and are used as featured images of the articles but they are not attached to those articles. In other words their post_parent = 0.
I need a way to reattach those images to the posts they are set as featured image.
So for each image with post_parent = 0, i have to find the post_id of were they are featured and update post_parent of the attachment to match the post ID.
I'm not a programmer, i understand what needs to be done but i don't know how to code it. If anyone can help with an example it'll be great. thanks! | Interesting task to solve this SQL only! So I found the following way and it worked in my local instance with testing data. Try it out and have a backup ready before running it for your complete site.
UPDATE wp_posts AS p
INNER JOIN (
SELECT p.ID AS attachment_id, pm.post_id AS post_id
FROM wp_posts p
JOIN wp_postmeta pm
ON pm.meta_value = p.ID
WHERE (
pm.meta_key = '_thumbnail_id'
AND
p.post_type = 'attachment'
AND
p.post_parent = 0
)
) AS b ON p.ID = b.attachment_id
SET p.post_parent = b.post_id
What this does is the following: (images are posts)
* `SELECT` all posts that are of type `attachment` and have a parent `0`
* all those posts should also be related to another post via the key `_thubmnail_id`
* `UPDATE` the posts, set `post_parent` to what it got from the `_thumbnail_id` relation
Thanks to this answer, for getting the sub-query into the `UPDATE`. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "images, post thumbnails"
} |
Why does the_post_thumbnail output full sized images after activating post-thumbnails support?
I mean:
add_action( 'after_setup_theme', 'thumbs_setup' );
function thumbs_setup() {
add_theme_support( 'post-thumbnails' );
}
My media settings are 150x150px on thumbnails, but now `the_post_thumbnail()` will output a full sized image instead. Why?
I see that the only way to have `the_post_thumbnail()` to really output the thumbnail size is to explicitly pass it:
`the_post_thumbnail('thumbnail')`
Why? | I think adding support to 'post-thumbnails' also adds a new type of size: 'post-thumbnail'. But 'post-thumbnail' **is not** == 'thumb' or 'thumbnail', it's a new, different type. Also, `the_post_thumbnail()` if called without params will output the 'post-thumbnail' size instead of the 'thumb' size.
'thumb' (or 'thumbnail') are setted via admin media panel, while 'post-thumbnail' is not.
Since the 'post-thumbnail' size is not yet setted, than `the_post_thumbnail()` doesn't really know what size to use, and thus it will output the full image.
To set the 'post-thumbnail' size you must use standard `add-image-size()` passing 'post-thumbnail' as the name, or, just use `set_post_thumbnail_size()`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post thumbnails"
} |
HTTP Security Headers in wp-config
Is there a way to place the HTTP Security Headers in `wp-config.php` instead of in `.htaccess` or `functions.php`? If so, what is the format? | The `.htaccess` file is read by the Apache server software before it even hands over to WordPress to generate a page. It is by far the best place to have your security headers.
That said, WordPress does have a class to modify the headers before they are send to the browser. This class contains a filter which you could use in a plugin. Beware that this filter might be bypassed if your page is served by a caching plugin (or some server level form of caching).
The `wp-config.php` file has a fairly narrow scope, as you can see in the codex. Defining security headers there is not among the possibilities.
Bottom line: yes, there are some ways to set security headers within WordPress, but make sure your `.htaccess` is in order. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "security, headers"
} |
Creating a simple button inside of a widget
So I'm wanting to add a couple of buttons in a footer text widget. It should be a really easy task by just creating a class inside of a link, and then styling it with CSS, like this:
`<a href="/newsletter" class="news-button">Newsletter</a>`
`a.news-button { width: 150px; height: 40px; border: 2px solid #000; border-radius: 3px; display: block; text-decoration: none; text-align: center; padding: 10px 0 0 0; font-size: 24px; color: #000; }`
Normally, this would work fine, like in this JS Fiddle: <
However in my WordPress widget, `.et_pb_widget a` is overriding everything else. And if I tried to just apply CSS to `.et_pb_widget a`, it's going to add it to all my widget links, which I do not want.
I even tried adding `!important` (I know, that's bad practice) but it still didn't work. I'd rather avoid a plugin for something this simple. Any ideas?
Link: < (footer, bottom right widget) | why not tie them all together?
.et_pb_widget a.news-button {
color: green; //example color.
text-decoration: none;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets, css, html, links, buttons"
} |
Can I trigger the publish_post hook by using wp_insert_post?
I'm writing a plugin that fetches some data from an XML file and then creates a post based on its content.
I was thinking of using `wp_insert_post()` to publish the new post, but I have some functions that are hooked to `publish_post`.
After digging in the `\wp-includes\post.php`, I couldn't find any `publish_post` action hooks that are triggered by this event.
There were only these hooks related to my case:
// Fires once an existing post has been updated.
do_action( 'post_updated', $post_ID, $post_after, $post_before);
// Fires once a post has been saved.
do_action( 'save_post', $post_ID, $post, $update );
//Fires once a post has been saved.
do_action( 'wp_insert_post', $post_ID, $post, $update );
Am I missing something? Or doesn't `wp_insert_post()` trigger the `publish_post` action? | It's triggered in `wp_publish_post()` that calls:
wp_transition_post_status( 'publish', $old_status, $post );
that fires up action calls, dynamically with:
do_action( "{$new_status}_{$post->post_type}", $post->ID, $post );
where `"{$new_status}_{$post->post_type}"` becomes `"publish_post"` in your case. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "hooks, wp insert post"
} |
Custom WordPress install - activate custom theme
I'm coding my own custom install.php (wp-content) and I want to be ablt to activate my custom theme when an install is running. Right now I've tried switch_theme('theme-slug') which works, however when I first log in to my admin panel, all the admin pages under Settings etc. is gone, so something is not right. If I remove switch_theme function from my install.php, then it tries to activate "twentyseventeen" however it can't find that theme, and that's because I've removed it from the themes folder, because I want to activate my own theme called "mastertheme".
Can somebody help me on how to activate my own theme when WordPress installs? | Twenty Seventeen is the default theme if no default theme has been defined. line 359 from _wp-includes/default-constants.php_
if ( !defined('WP_DEFAULT_THEME') )
define( 'WP_DEFAULT_THEME', 'twentyseventeen' );
You do not need to edit that file, however, to change this.
Simply define your theme in the file _wp-config.php_ just before this line:
`require_once(ABSPATH . 'wp-settings.php');`
Like so:
define( 'WP_DEFAULT_THEME', 'my-new-default-theme' );
require_once(ABSPATH . 'wp-settings.php'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development"
} |
Rewriting rules: difference between 'init', 'rewrite_rules_array', 'generate_rewrite_rules'?
I was wondering, what's the difference, and best filter/action to add rewrite rules? I used all but I still can't say why should I use one or the other.
add_action('init', 'add_rewrite_rules'); // or:
add_action('generate_rewrite_rules', 'add_rewrite_rules'); // or:
add_filter('rewrite_rules_array','add_rewrite_rules'); | Use whatever is simplest for your needs.
If you just need to add a rule to the stack, use `add_rewrite_rule` on `init`.
`generate_rewrite_rules` and `rewrite_rules_array` give you access to the whole rewrite rules array. Use these if you need to modify, remove, or reorder the rules. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "url rewriting, rewrite rules"
} |
How to see if event is featured in PHP?
I'm using The Events Calendar by Tribe. What I'm looking for is a way to see if an event is featured without using the shortcode and rendering their markup. Is there a conditional available such as `tribe_is_featured_event()` or something along those lines? I have not been able to find anything online regarding this. As a last resort, I will make a call to the database although I'm not sure where this is stored. | I believe you would want to use this function (from `the-events-calendar/src/Tribe/Featured_Events.php:45`):
/**
* Confirms if an event is featured.
* @param int|WP_Post $event
*
* @return bool
*/
public function is_featured( $event = null ) {
$event_id = Tribe__Main::post_id_helper( $event );
if ( ! $event_id ) {
return false;
}
return (bool) get_post_meta( $event_id, self::FEATURED_EVENT_KEY, true );
}
I've never used the plugin, but it seems like you would use it like this (giving it the $post object or the post id):
if( Tribe__Events__Featured_Events::is_featured( $post ) ) {
// it's featured!
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "the events calendar"
} |
How I can open back door for myself?
I hired a developer to edit a specific plugin in my website. As we all know he can't edit the code of that plugin without giving him key-master/administration permeation.
He can at any time to delete my account and take the whole control of my website, I made a plan B and made a backup for my whole website, If anything goes wrong I will delete my whole website from cpanel and make a setup from the backup.
My question is: How I can make myself un-deletable, or made a second door for myself to access my website if he decide to delete my account? | Of course,someone can editing code plugins via the editor and build the shell or somethings like that but I don't they can able to hack your database. Just simple, you can permit developer with specific user role. But I think the best way is using an isolated local install for developing the plugin: xampp,etc... | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "security"
} |
Execute shortcode only once in the page
Is there a way to prevent more than one shortcode to run in the same page? If shortcode is already been executed not to run another.
add_shortcode('foo', 'foo_add_player');
function foo_add_player($atts){
//do not run twice
} | Set a flag like `$already_run` to static and give it an initial value `false`. Then check if that value is true. If not, do the one-time thing and then set `$already_run` to `true`. The next time this function is called, it will not re-assign the static property, but will instead use the value set at end of code. So it will skip second and subsequent calls.
function foo_add_player($atts) {
static $already_run = false;
if ( $already_run !== true ) {
// do stuff here
}
$already_run = true;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "shortcode"
} |
How can i get the post's full html source by its ID?
Is there a way that i can get the HTML source of a single post dynamically from within WordPress site?
for example, if i wanted an external html I would use:
file_get_contents($url)
or using cUrl, But I'm looking for a way to do it from within my WordPress to get full qualified HTML for one of my posts
Is that possible ?
Thanks in advance | If you have the post's ID, I assume that you are the owner of the blog ( Not because others can't have the ID, but because only the owner should do such tasks ).
To convert the post ID to the post's URL, you can use `get_the_permalink()`:
$url = get_the_permalink( $id );
Afterward, you can use `file_get_contents()` to fetch its content, including the full source of that web page. So, your full code will be:
$url = get_the_permalink( $id );
$data = file_get_contents( $url );
Which data is your HTML source. Note that this will only work in the WordPress environment. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, plugin development, html, curl"
} |
Disable permalinks on all pages and posts
As I am using the JSON API, the permalinks don't make sense. My site URLs are totally different to the ones generated by the permalinks, so this is likely to confuse the client.
Is there any way I can disable permalinks on pages and on the default post type? I was able to do it on custom post types by specifying `'public' => false` but how do I make this change site-wide? Even the media pages have a permalink. | Since WP 4.4, there is a hook you can use to edit default arguments for registered post types:
`register_post_type_args` (view in context on trac)
If you're wanting to remove the permalink/slug from the edit post/page screens but not remove posts from the admin menu itself, setting `public => false` and `show_ui => true` should do that.
function remove_from_public( $args, $post_type ) {
$args['public'] = false;
$args['show_ui'] = true;
// some other common uses:
//$args['show_in_rest'] = false;
//$args['rewrite'] = false;
//$args['rest_base'] = false;
return $args;
}
add_filter( 'register_post_type_args', 'remove_from_public', PHP_INT_MAX, 2 );
I use `PHP_INT_MAX` just to kick it to the bottom of the hook to overwrite anything that may be getting called there. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "permalinks"
} |
How do I edit the side-bar (doesn't seem to be a menu)?
. I am fairly new to WordPress so I'm not quite sure where to change this. I've gone into the widgets and the side menu however the only thing that shows is the php for the donate button.
I only need to edit the side bar highlighted in red, which seems separate from the "side bar" below it. The only side menu listed in widgets is the one with the Donate link.
Thanks. | Please also check the sidebar.php as well the header.php file in the theme root directory.
On first sight it seems that its a header section which also includes the vertical menu. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sidebar"
} |
What permastrusture tags are generated out of the box right after creating custom post types and taxonomies?
I was curious: when I create a custom taxonomy or post type, what new permastructure tags are auto generated and ready to use? It seems there are no docs about. | Ok one way to check them up is to log them somewhere after creating post types and taxonomies:
add_action('init','register_customs');
function register_customs(){
// [...] create types and tax
global $wp_rewrite;
// log $wp_rewrite somewhere
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, url rewriting, tags, rewrite rules"
} |
create filter in functions.php
I want to create a filter in my functions.php theme to change the URL of $icon_html in this plugin function.
public function get_icon() {
// paypal icon
$icon_html = '<img src="paypal.png" />';
return apply_filters( 'woocommerce_gateway_icon', $icon_html, $this->get_id() );
}
How to perform this? $icon_html is not unique.
Thank you, Thibault | Whenever you see `apply_filters( 'filter_name', $value )`, you can use `add_filter()` to replace or modify the value of `$value`:
add_filter( 'filter_name', 'callback_function' );
Where `callback_function` is a function that you create. That function will accept `$value` as an argument, and needs to return a new value. So for your example, that will look like this:
function wpse_275788_replace_icon( $icon_html, $id ) {
$icon_html = 'Put new icon html here.';
return $icon_html;
}
add_filter( 'woocommerce_gateway_icon', 'wpse_275788_replace_icon', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, themes, filters"
} |
How do I locate specific part of code that affects ssl?
I recently migrated my old website to this domain: <
The ssl works fine but in the console of google inspector it suggest that there is a .gif file that should be renamed from http to https.
, I can see the setting in its 2nd screenshot: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, ssl"
} |
change database to multisite in localhost
I have a WordPress installation to test before uploading to the server, but now I'm trying to make it Multisite.
I want to make the blog where I'm working on a subdomain but I don't want to delete all the posts I already have. I already have Multisite active.
Is there any way to do that? | So just to clarify, you've already setup the multisite by following: <
And the multisite is working and you can create subdomains. But you want your current site to be a subdomain?
If so, I think the best way to do this will be to create the new sub site first, then use a cloning/migration plugin to copy all your data from your current site to the new sub site. WordPress has it's own export-import plugin:
<
The WordPress Importer will import the following content from a WordPress export file:
* Posts, pages and other custom post types
* Comments
* Custom fields and post meta (this will include your post thumbnails and attachments).
* Categories, tags and terms from custom taxonomies
* Authors
Then you can remove all the data on your root site.
There are other cloning/migration plugins if you don't like the WordPress importer. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite"
} |
Wordpress as a backend for external service?
I created php REST API for old windows application of our company.
Through the REST API I display data on a web page.
I want to manage our data through Wordpress, like classic custom post with custom fields
**My concept:**
1. Loading data over REST API into WP backend (I don't want save these data to WP database)
2. Show list custom post (like from Wordpress DB)
3. Edit and Save post to REST API, not to Wordpress DB
It's possible? If so, how? | Yes, you could create a plugin to produce admin pages that connect to the REST you've made for your application, and provide a gui to interact with its endpoints for CRUD operations. It would be, essentially, no different than connecting to any other external api (i.e. a Mailchimp or Google api).
If you are only looking to provide a gui for interacting with your windows application, there may be less constrictive options. (ng-admin comes to mind)
If, however, your application has other tie-ins to a wordpress install (data lookup relevant to some other content management operation for instance), then look into the Plugin Developer's Handbook.
You may need to create custom capabilities for user roles to manage access to your CRUD operation endpoints.
Also see: Administration menu a page creation.
And of course the HTTP API. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, api"
} |
add_rewrite_rule not working for language specific characters
My default search query:
example.com/search/?search_text=keyword
What I want to transform it:
example.com/search/keyword
So I added this to my `function.php`
add_rewrite_rule('^search/([^/]*)?','index.php?pagename=search&search_text=$matches[1]','top');
Works fine for english alphabet but whenever I search a keyword in my language like this:
example.com/search/kırmızı
The title of the page becomes: `k%C4%B1rm%C4%B1z%C4%B1` and no results returned.
Let me know if you need more details. | This is happening due to encoding. I assume you have a function in your search page, which you get and use `search_text` inside that template. You should decode the URL before doing so.
The `urldecode()` function would be what you are looking for. Your string is also UTF-8 encoded, so this is what you are going to need:
$string = utf8_decode( urldecode( $_GET['search_text'] ) );
Now you can use the decoded string in your search. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "url rewriting, search, urls, rewrite rules, encoding"
} |
Add css code in admin_enqueue_scripts
How can I add css code to `admin_enqueue_scripts`? I did this for `login_enqueue_scripts` its working fine but same thing is not working for `admin_enqueue_scripts`.
Following is my code snippet
add_action( 'admin_enqueue_scripts', 'custom_css_stuff' );
function custom_css_stuff() {
?>
<style type="text/css">
body { color: red; }
</style>
<?php
}
?>
This is not changing font color of body. am I missing something or is there any other way to do this? | If you're using the `admin_enqueue_scripts` hook, use wp_enqueue_script() to enqueue a CSS file with the styles you want to apply.
If you want to output a `<style></style>` element use the admin_head hook to output it between the `<head></head>` tags:
function custom_css_stuff() {
?>
<style type="text/css">
body { color: red; }
</style>
<?php
}
add_action( 'admin_head', 'custom_css_stuff' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp admin, admin css"
} |
How to Display Post Excerpts in Admin by Default?
By default in the admin the Excerpt is hidden. See below.
 {
$unchecked = get_user_meta( $user->ID, 'metaboxhidden_post', true );
$key = array_search( 'postexcerpt', $unchecked );
if ( FALSE !== $key ) {
array_splice( $unchecked, $key, 1 );
update_user_meta( $user->ID, 'metaboxhidden_post', $unchecked );
}
}
add_action( 'wp_login', 'wpse_edit_post_show_excerpt', 10, 2 );
This will update user's meta ( after successful login ) by removing `postexcerpt` name from the array of unchecked boxes names.
**Note** : to avoid losing your change, create a child theme and put the code into its `functions.php`. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "wp admin, excerpt"
} |
Use title of post as argument for query
I want to use the title of the actual post as argument parameter for a `wp_query`.
I already tried to set it with `the_title` or `get_the_title()` but it does not work. Is it possible to save the title as a string and set it as argument parameter?
$arguments = array(
'tag' => the_title(),
'cat' => '1'
);
$query = new WP_Query( $arguments );
while ( $query->have_posts() ) {
$query->the_post();?> | Yes! You meant to use `get_the_title()` which returns the title as a string. `the_title` instead outputs it to the browser. The same is true of many other functions in WordPress, e.g. `the_post_thumbnail` vs `get_the_post_thumbnail` or `bloginfo` vs `get_bloginfo`
For future reference, a search on < will usually reveal related functions | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, get the title"
} |
Show with echo if a post has two or more categories
I am not exactly an expert in php and less in wordpress. I wanted to know if they are so kind that I have a fault. I explain, my problem is that I want to display a div with echo in a post if it has these two categories (or more). I am attaching the code. Thank you very much and greetings!
<?php
$bflower = "This is a A";
$bmammal = "This is a B";
$cflower = "This is a C";
$cmammal = "This is a D";
if(has_category(array('chicken', 'mammal'))){
echo $cmammal; }
elseif (has_category(array('jasmin', 'rose'))) {
echo $cplant; }
elseif (has_category(array('aloe vera', 'jeran'))) {
echo $bplant; }
elseif (has_category(array('rabbit', 'cow'))) {
echo $banimal; }
else
echo "No";
?> | To answer your question, if placed within the Loop - after, typically, `while ( have_posts() ) : the_post();` in a single.php file - the code will work as follows:
* The `has_category( array( 'x', 'y' ) )` condition will be satisfied if the post is in either x or y, or both, regardless of whether it is in any other categories (assuming an otherwise unmodified main query and no other conditions).
* In your example, if the post was in both "jeran" and "cow," then `$bplant` would be echoed, but not `$banimal.` I think you probably already understand why.
* If a post must have **both** of the two categories, then you'll have to work the logic out accordingly- e.g., `if ( has_category( 'x' ) && has_category( 'y' ) )`, etc.
You might also conceivably run into problems with unique approaches to "single post pages." | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "posts, categories"
} |
Post url rewriting for posts with certain category
Attempting to create a custom rewrite rule for any post that has a category of Shop. The posts use `/%postname%/` but I want `/shop/%postname%/` to appear in the url. Below is what I have but I can't get it working.
add_filter( 'post_link', 'custom_permalink', 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
// Get the categories for the post
$category = get_the_category($post->ID);
if ( !empty($category) && $category[0]->cat_name == "Shop" ) {
$permalink = trailingslashit( home_url('/' . $post->post_name ) );
}
return $permalink;
}
add_action('generate_rewrite_rules', 'custom_rewrite_rules');
function custom_rewrite_rules( $wp_rewrite ) {
$new_rules['^shop/([^/]*)-([0-9]+)/?'] = 'index.php?postname=$matches[1]';
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
return $wp_rewrite;
} | generate_rewrite_rules didn't work for me at all and I found posts on forums where others were having the same issue. Adding to the rewrite_rules_array did work. Below is the solution.
add_filter( 'post_link', 'custom_permalink', 10, 3 );
add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('init','flushRules');
function custom_permalink( $permalink, $post, $leavename ) {
$category = get_the_category($post->ID);
if ( !empty($category) && $category[0]->cat_name == "Shop" )
{
$permalink = trailingslashit( home_url('shop/' . $post->post_name ) );
}
return $permalink;
}
function flushRules(){
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
function wp_insertMyRewriteRules($rules)
{
$newrules = array();
$newrules['^shop/(.*)$'] = 'index.php?name=$matches[1]';
return $newrules + $rules;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, url rewriting"
} |
wp_insert_posts keeps adding multiple pages
I have a function that creates a page but I only want one page and the code below keeps adding multiple pages (2 at a time). Is there a way to only add one post? I tired this solution but it didn't work.
$my_post = array(
'post_title' => 'My page Reql',
'post_type' => 'page',
'post_name' => 'archive',
'post_content' => 'This is my page reql.',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 1,
'menu_order' => 0,
'guid' => site_url() . '/archive' );
$PageID = wp_insert_post( $my_post, FALSE ); // Get Post ID - FALSE to return 0 instead of wp_error. | You can check whether the page exists or not, and create it only if it doesn't already exist. `get_page_by_title()` can help you in this case:
// Check if the page already exists
if( ! get_page_by_title('My page Reql') ) {
// The page doesn't exist, so let's create it
}
Also, you might want to investigate how are you calling the function. You might be calling it twice, that might be the reason it's creating a copy of each post. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "functions, pages"
} |
Determine the last child of the parent menu WP Nav Walker
Is there a way to add a condition to know if the current item of the navigation walker is the last child of the menu or parent?
| Item 1 | Item 2 |
| - Item 1.1 | - Item 2.1 |
| - Item 1.2 | - Item 2.2 |
| - Item 1.3 |<----------------- Determine if current item is last child
For example:
if ($item->last_child(of_current_parent) {
...
}
So, how do you determine if the current item is the last child of its siblings?
EDIT: Solved my problem trying this: < But had to change the logic quite a bit to fit my needs. See my answer below. | Okay, so I solved my problem using this link: < The example only shows how to add classes to the last child of its siblings. But want I want to do is to modify how the last child displays.
Though this is the closest to what I'm looking for, I just had to modify some logics of this code.
I also encountered some problems displaying the item title. What I did was, instead of using `$item`, I used `$element` in `function display_element()`. For example (retrieving the item's url): `$element->url` instead of `$item->url`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "menus, navigation, walker"
} |
Is it possible to set a different frontend- and backend-language?
my WordPress site is currently set to "English". I like the back-end to be completely in English, so it is easier to follow tutorial instructions etc. However, the front-end must be in German due to different reasons.
For instance, in need to have `lang="de-DE"` in the HTML-header for some plugin to work correctly.
Is there a way to achieve this? | You can set the site language to whatever you wish in the `Settings > General > Site Language`.
After that, you can head over to your profile and choose a language for the back-end. To do so, head over to `Users > Your Profile > Language` and change it to English.
However, there is an issue with Admin-Ajax requests. If you set the back-end language to English, the Ajax requests will be in English too. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "localization, language"
} |
Where is script-loader.php creating JS tags
I have a script being auto created in wp-includes/script-loader.php
This is jquery that wordpress depends on as well as some plugins for the site
$scripts->add( 'jquery-core', '/wp-includes/js/jquery/jquery.js', array(), '1.12.4' );
I need to add `defer` to the tag where this is created, I tried removing it and moving to the head but wordpress as well as the dependent plugins break as if its totally missing.
I assume its code like this, just not sure which to change:
$src = $wp_scripts->base_url . "/wp-admin/load-scripts.php?c={$zip}&" . $concat . '&ver=' . $wp_scripts->default_version;
echo "<script type='text/javascript' src='" . esc_attr($src) . "'></script>\n";
Any ideas. Thanks. | add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( 'jquery-core' !== $handle )
return $tag;
return str_replace( ' src', ' defer="defer" src', $tag );
}, 10, 2 );
Provided by: toscho | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "javascript"
} |
Reusable content block
There is a content block that I wish to put on certain pages.
This content block needs to be managed in WordPress. I'm not sure where it should be situated in the admin. It's not really a custom post type, i.e. it doesn't have any sub posts. It's literally just a block that contains a heading, some text and some logos.
I have use of Advanced Custom Fields if this helps and I'm using WordPress with the JSON API. | if you're using ACF, create an options page and then add a field there. Then present that data in a side widget by echoing out the field.
once the field is created you can call it with this code:
<?php the_field('page_content', 'option'); ?>
I like to add it to a function
function rt_show_field() {
$field = '';
if (get_field('page_content', 'option')) {
$field = get_field('page_content', 'option');
}
return $field;
}
add_shortcode( 'my-field', 'rt_show_field');
Then if you add that function to your functions.php
you can simply add this short code to a widget
[my-field]
or add the function
echo rt_show_field();
to a template page or whereever you want. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp admin, content"
} |
If else statement based on date_diff value
I have a problem with dates.
I need to add if-else logic to show different content.
It's based on `date_diff` values. And here's go a problem:
I need to show button if today's date - post_modified date >= 3 hours And if it's less than 3 hour difference - show default message: "Wait for x minutes before using button".
Here goes my efforts:
<?php
$now = new DateTime();
$currentDateTime = $now->getTimestamp();
$postUpdated = $post->post_modified;
if ($currentDateTime - $postUpdated >= 1) :
?>
<button>Some value</button>
<?php else: ?>
<p>Wait, please</p>
<?php endif; ?>
Hope u can help me. Thank you. | You can use `strtotime()` to convert the time to an integer, and then do a conditional.
// Get the current time
$now = strtotime("now");
// Convert post's modification time to int
$postUpdated = strtotime( $post->post_modified );
// Check if 3 hours has passed, each hour is 60*60 seconds
if ( $now - $postUpdated >= 3*60*60 ) {
// First conditional
} else {
// Second conditional
}
Also, if the time's format is known ( which is usually 0000-00-00 00:00:00 ), you can directly use `strftime()`. Here is a quick example:
$timestamp = strftime("%Y-%m-%d %h:%M:%S %a", time() - 3*60*60);
Now you have a formatted value of 3 hours before, which you can use in `date_diff()`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "date time"
} |
change text "free shipping" in WooCommerce
Recently we give free shipping to all german customers but bill the austria and switzerland. On our product pages we show the free shipping, but as needed for german law, it must be called "free shipping in Germany". Where can I change this text?
Couldnt find a solution in WooCommerce setting nor in WooCommerce German Market Plugin. Thanks for help! | I found this answer . Hope this will help you. maybe with wpml for multi-lang
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Create a WordPress template without navigation and footer
As the title suggests, I'd like a page template to have NO navigation and NO footer.
All my page templates have this:
<?php
/*
* Template Name: Blah Blah
*/
if (!defined('ABSPATH'))
exit; // Exit if accessed directly
get_header();
?>
But if I remove the above code then the entire page won't work. | Don't remove `get_header()`.
Duplicate the `header.php` to `header-{custom-name}.php`, let's say (`header-nonavfooter.php`) then in the template file replace `get_header()` with **`get_header('nonavfooter')`**.
In the new header file (`header-nonavfooter.php`) remove the code related to navigation.
Do the same for the `footer.php` also(Create a new footer.php and remove the footer parts that you don't need), remember not to remove `wp_footer()` available in `footer.php`. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "templates"
} |
How to set a Background image in Wordpress?
I want to set a background image (jpeg) for my home page only and not for the whole site. Right now it is white color for the whole site. This is the code in function.php:
// Background color
$background_args = array(
'default-color' => 'ffffff',
);
add_theme_support( 'custom-background', $background_args ); | The way I see, you have 3 options:
* You can achieve that with CSS. Just target the div you want to put the background in. Target it in a way that only shows at the home of the site (check the ID and class of the body div, it usually has names like 'home-template' and such.
* You can achieve that with HTML. You can 'hard-code' the style inline, in your PHP file, like you would do in a HTML one. You can do that, if the body of the document is in a file that _is not header.php_.
* (recommended) You can achieve that with PHP using 'is_front_page' (< Just do a conditional that checks if the page is the front page. If it is, you can attach and ID to the body, or style it inline. Else, just use the regular body. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images"
} |
WooCommerce - different icons for product categories
I have difficulties with changing icons of product categories in my sidebar widget. I was browsing many forums but i couldnt find any good answer for this.  | It is a background of category listing li. it will change using css. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Change home-url in dashboard
I am wondering if I can change the URL of the "Home"-button in the dashboard's admin-bar.
, but it would be nice to prevent having to run that javascript redirect, also because it creates waiting time for the user.
I tried the following things, to now luck:
Change homepage url
How to change the Admin-bar's link target? | Try this. Even if you want to change "View Site" link then remove "site-name" and add "view-site" in get_node. Thanks.
add_action( 'admin_bar_menu', 'customize_my_wp_admin_bar', 80 );
function customize_my_wp_admin_bar( $wp_admin_bar ) {
$site_node = $wp_admin_bar->get_node('site-name');
//Change link
$site_node->href = home_url().'/velkommen';
//Update Node.
$wp_admin_bar->add_node($site_node);
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "admin, admin bar"
} |
Can I submit a plugin that follows the PSR-2 coding style guide?
Can I submit a plugin that follows the PSR-2 coding style guide?
**This**
if ($a === $b) {
}
$array = ['foo', 'bar'];
**instead of**
if ( $a === $b ) {
}
$array = [ 'foo', 'bar' ]; | I would guess to the official plugin directory? Yes, the WP's own coding standards are recommended, but not required:
> 4. Keep your code (mostly) human readable.
>
>
> Intentionally obscuring code by hiding it with techniques or systems [...] Minified code may be used, however the unminified versions should be included whenever possible. We recommend following WordPress Core Coding Standards.
>
> <
PSR-2 is perfectly readable and there should be no issue with using it. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "plugin development"
} |
Hide disclaimer from summary excerpts
I have a system that works well for me where I can add a tag of affiliate to a post and then this code in my functions.php file adds a disclaimer to the beginning of the post:
`/* Add disclaimer to top of POSTS that contain affiliate tag */ function tt_filter_the_content( $content ) { if (has_tag('affiliate')) $custom_content = '<hr><p><em>Disclosure: This post contains affiliate links and we may receive a referral fee (at no extra cost to you) if you sign up or purchase products or services mentioned.</em></p><hr>'; $custom_content .= $content; return $custom_content; } add_filter( 'the_content', 'tt_filter_the_content' );`
I've been using this method for a while and it works great. However, I noticed that on my summary excerpts and my feed, it shows that disclaimer as well. That makes it a little messy and cuts away from a lot of the summary text showing up.
Is there a way to filter this out from being applied to the summary and my RSS feed? | You could do something like this:
/* Add disclaimer to top of POSTS that contain affiliate tag */
function tt_filter_the_content( $content ) {
if (has_tag('affiliate') && is_single())
$custom_content = '<hr><p><em>Disclosure: This post contains affiliate links and we may receive a referral fee (at no extra cost to you) if you sign up or purchase products or services mentioned.</em></p><hr>';
$custom_content .= $content;
return $custom_content;
}
add_filter( 'the_content', 'tt_filter_the_content' );
Now you are checking if the tag exists and if it's a single post. If this still shows up in the feed, then you can change the if statement to something like:
if ((has_tag('affiliate') && is_single()) && !is_feed()) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, filters, shortcode, excerpt, rss"
} |
WordPress get_the_content get child element like p value
I am developing web site by wordpress in case my problem I want to remove h1 and h2 tag in from main page. I want to get only child p tag by `get_the_content()`
<p id="main">
<?php
echo wp_trim_words(get_the_content(),20, '...' ); ?>
</p>
Main Page get the content from this page
<h1 class="entry-title">Set and Furniture Design</h1>
<h2 class="green-pd">Set Design</h2>
<p id="para">A Bachelor pad was to be designed for a cookery show called 'Cook na kaho' for the Star One TV channel. Props for same were purchased from various home stores and the set was installed with in four days of starting work.</p>
<h2 class="green-pd">Furniture Design</h2>
<p>The 600mm X 1500mm rectangular centre table used the Indian screen called jaaliwork as supports to the table top for breaking the monotony of solidity and straight lines.</p>
Please help me
Thank you... | Wordpress function **get_the_content** automatically remove html tags from the content, So fetch only **p** tag content is not possible with using this function. you can use **post excerpt** to fulfill your requirement.
**Each post has section in admin called Excerpt** _It you are unable to see the section in the admin please check **screen option** while editing the post_
$my_excerpt = get_the_excerpt(); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "the content"
} |
Should i clear the plugin cache for cache busting?
I need to understand the correct way to use cache busting, because i know that i can use a query string for version which changes in every file update, but i prefer to use cache busting through changing file name, so i created program to generate a new file with a new numbered name on every update and it works perfect but the problem is that i have to clear the cache of a caching plugin, So is this the normal way to use cache busting or it should be working another way automatically? | The main obvious problem with your scheme is that when someone wil try to reload an old page it will get all kinds of 404 when requesting the JS and CSS since those files are not on the server anymore.
There is seriously no need to reinvent the wheel, just follow WordPress's best practice unless you have an **excellent** reason to deviate. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "theme development, cache"
} |
Run a php file daily at specific time
I'm trying to add a cron job to run file daily at 7pm.
How can i add the file run command and specify to run it at 7pm ?
// Scheduled Action Hook
function run_my_script( ) {
// run my file : mysite.com/cron.php
}
// Schedule Cron Job Event
function USERS_MONITORING() {
if ( ! wp_next_scheduled( 'USERS_MONITORING' ) ) {
wp_schedule_event( time(), 'daily', 'USERS_MONITORING' );
}
}
add_action( 'wp', 'USERS_MONITORING' );
I don't know if there is a better solution. | You can include the PHP file and do the tasks, if WP-cron is your only option.
// Scheduled Action Hook
function run_my_script( ) {
require_once('related/path/to/php/file.php');
}
// Schedule Cron Job Event
function USERS_MONITORING() {
if ( ! wp_next_scheduled( 'USERS_MONITORING' ) ) {
wp_schedule_event( strtotime('07:00:00'), 'daily', 'USERS_MONITORING' );
}
}
add_action( 'USERS_MONITORING', 'run_my_script' );
Note that you need to include the related path. If you want to access the PHP file by its URL, you need to use cURL instead.
Also, as @rarst mentioned in one of his posts:
> **Note :** WP Cron isn't guaranteed to run at precise time since it is trigerred by visits to the site. I am not confident if recurrent runs will "stick" at midnight or will slowly slip from there, you might need to readjust periodically. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "wp cron"
} |
Getting failure when using filemtime() with wp_enqueue_style
I am trying to change the stylesheet file version using the `filemtime()` function with the `wp_enqueue_style` with the following snippet
function pro_styles()
{
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory_uri() .'/child-style.css'), 'all' );
}
add_action( 'wp_enqueue_scripts', 'pro_styles' );
but it is throwing a warning
> Warning: filemtime(): stat failed for.....
While i am sure that the file exists | It's because you're retrieving it via URL, but `filemtime()` requires a path. Use `get_stylesheet_directory()` instead. That returns a path:
function pro_styles()
{
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' );
}
add_action( 'wp_enqueue_scripts', 'pro_styles' ); | stackexchange-wordpress | {
"answer_score": 29,
"question_score": 13,
"tags": "theme development, cache"
} |
how to check plugin name unique or not?
I am new in WordPress but I wanted to know how to check my plugin name is unique or not and how to upload this plugin in wordpress.org. Please guide me how is it possible. ? | First visit ` to see if your desired slug is in use by an existing plugin. If it exists and you don't want to change the name, a -2 will automatically be appended when you submit your plugin and it passes review.
Your plugin must be GPLv2 licenced or GPLv2 compatible and under 25mb when zipped.
Log into your wordpress.org account and submit your plugin here. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, wordpress.org"
} |
Is there any way to add placeholder for WordPress Customizer text input fields
I am wondering if it is possible to add placeholder text for WordPress Customizer input fields especially text and textarea fields.
I have added a input control by the code below. Can anyone tell me how I can add placeholder text to the input field?
$wp_customize->add_control('directorist_address', array(
'label' => __('Address', 'directorist'),
'section' => 'directorist_contact',
'settings' => 'directorist_address',
'description' => __('Enter your contact address. Eg. Abc Business Center, 123 Road, London, England'),
)
);
The code above output an input field like below:
,
'section' => 'directorist_contact',
'settings' => 'directorist_address',
'description' => __('Enter your contact address. Eg. Abc Business Center, 123 Road, London, England', 'directorist' ),
'input_attrs' => array(
'placeholder' => __( 'Placeholder goes here...', 'directorist' ),
)
)
); | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 5,
"tags": "theme customizer"
} |
WordPress Plugin Update Process
I am developing a wordpress plugin which involves creating a table in the wp database.
I have included an uninstall.php file to remove the table from the wp database when the user decides to delete the plugin from wp admin dashboard.
The thing is that,i want to know whether the uninstall.php file is executed during the update process if i provide an update through the wp plugin repository | No it does not. The uninstall.php file will only be run if a user deactivates the plugin and clicks the delete action.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, updates"
} |
How to append the excerpt to the content in the single post page?
For every Post, I have content and excerpt. I am trying to figure out how to include both of these in the single post page.
So far this is what I have:
function after_post_content($content){
if (is_single()) {
$content .= 'I need the excerpt to be displayed here.';
}
return $content;
}
add_filter( "the_content", "after_post_content" );
Any help in how to add the excerpt of the Post below the content of the Post will be appreciated. | Here is how I did it:
function after_post_content($content){
if (is_single()) {
$content .= the_excerpt();
}
return $content;
}
add_filter( "the_content", "after_post_content"); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, loop, filters, hooks"
} |
Best Authetication between REST API and Mobile App
I am developing a mobile app, with WordPress REST API.
What is the recommended authentication method and plugin to use for?
here the list I found:
* OAuth 1.0a
* OAuth 2.0
* JWT Authentication
* Two-Factor Authentication | JWT Authentication is very Popular and easy to config. For Two Factor Authentication use this JWT Athhentication Plugin . | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "rest api, authentication"
} |
Custom content per post in widget
It's hard to explain, but I want to be able to do is fill in fields when creating a post, and these fields will populate a widget. So for each post the widget content is different and the widget content is inputted on the post - I don't want the plugins that show widgets only on certain posts - I have hundreds of posts and doing it that way would be a pain.
Does anyone know of a plugin that will achieve this? Free or paid I don't mind. | Your best bet there would be to register a custom widget which accesses the global `$post` object and outputs the specific meta fields for that post. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, widgets, plugin recommendation"
} |
Change Wordpress prefix for only one table?
I have a little question about Wordpress database.
I want to know: Can I change the wordpress pefix for only one table? Thet means I use on one Wordpress Page two Prefixes.
If it works how I want to work and anyone know how it works, please write what I can make that it works.
Why I need it? I have 2 Websites, on the first website can log in all users and on the second website can only log in a little part of this users. But the username and Password have to be the same.
Sorry for my bad English and thanks for the help! ;) | In `wp-config.php` for your second site, define the following two constants:
define('CUSTOM_USER_TABLE', 'yourfirstprefix_users');
define('CUSTOM_USERMETA_TABLE', 'yourfirstprefix_usermeta');
You'll have to add some custom logic to your second site limiting logins by user role. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "database, users, table"
} |
How do I locate specific file in a post that affects ssl?
I recently migrated my old website to this domain: <
It is a wordpress site and in the articles, example here: < in the console of google inspector it suggest that there is a .gif file that should be renamed from http to https.
 [R=301,L]
</IfModule>
The above is presented in lieu of tracking down the specific file, as the page no longer seems to be throwing the mixed content error. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, ssl"
} |
How to clone and locally run a network for testing
I have a live network installed on a remote web server. I am about to start writing some plugins for it but want to test that they behave before disrupting a live site.
I was thinking that I would clone the site (backup the database, download via FTP the files) and restore to localhost for testing. The remote site uses subdomains for blogs.
What steps do I need to take so that my clone behaves pretty much as the remote version?
What changes do I need to make so that it can run as localhost instead of as a remote URL? | You'll have to set up a domain with wildcard subdomains in your localhost (I usually set up thelivedomain.local), direct that to 127.0.0.1 in your hosts file and run the DB search and replace tool against your local copy of the site to safely replace the live domain with your localhost domain in the WP database, because it stores URLs in serialized arrays which can break with a search&replace against the raw SQL.
You'd also have to make sure that your localhost's PHP version is the same and that you have the same PHP extensions enabled in your local environment as on the live server. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, database, backup"
} |
Wordpress automatic Login on other page?
I have a littlee questions about Wordpress.
If I have several sites on one Webserver and all pages use the same "user table" and "user meta table", can I make if one user login on site one and then go to site two that the user automatically login on site two? If yes, how I can make this?
Sorry for my bad english and thanks for help! ;) | Yes, you can. Read my answer to similar question, here. This answer provides a solution for two sites, but can be used for any number of sites. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, database, users, login"
} |
Shortcode syntax errors
Trying to write a shortcode to create a gallery but I am getting a parse error. My `foreach` loop needs correction as well as returning the correct output. Any help please?
function allphotos_shortcode(){
$images = get_field('fl_gallery');
if( $images ) {
$output .= '<ul>';
foreach( $images as $image ) :
'<li><a href="' . echo $image['url'] .'"><img src="' . echo $image['sizes']['thumbnail'] . '" alt="' . echo $image['alt'] . '" /></a><p>' . echo $image['caption'] . '</p></li>'
endforeach;
$output .= '</ul>'
}
return $output
}
add_shortcode('allphotos', 'allphotos_shortcode'); | You're missing semicolons after `</li>`, `</ul>`, and `$output`. You also shouldn't be `echo`ing inside string concatenation and not adding the `<li>` tag to `$output`. The below is your code with these fixes.
function allphotos_shortcode(){
$images = get_field('fl_gallery');
if( $images ) {
$output .= '<ul>';
foreach( $images as $image ) :
$output .= '<li><a href="' . $image['url'] .'"><img src="' . $image['sizes']['thumbnail'] . '" alt="' . $image['alt'] . '" /></a><p>' . $image['caption'] . '</p></li>';
endforeach;
$output .= '</ul>';
}
return $output;
}
add_shortcode('allphotos', 'allphotos_shortcode'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "shortcode"
} |
Hiding by default posts in given category except for some cases
I have assigned to some posts a sort of "archived" category hence these posts shouldn't appear anywhere except when users access the "archive" page.
How can I achieve this? | wpse276485_exclude_archived($query) {
if ( !is_admin() && !is_category('archived') ) {
$query->set('category__not_in', array(get_cat_ID('archived')));
}
}
add_action('pre_get_posts','wpse276485_exclude_archived');
That should do it, assuming the name of your category is "archived". | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, filters"
} |
What hook do I use if I want to update a user profile field when a new user is created?
What hook do I use if I want to update a user profile field when a new user is created?
function default_followers() {
// set default follower
$current_id = get_current_user_id();
$key = 'followers';
$value = '1';
update_user_meta( $current_id, $key, $value);
}
add_action('????????????????', 'default_followers' );
Ive tried: personal_options_update
Ive tried: edit_user_profile_update
Neither seem to work. | You'd want to use the `user_register` hook, which fires immediately after the new user's username and (hashed) password are saved to the DB. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "hooks, profiles"
} |
Display post meta on edit page in admin
I've got a custom post type for contact form submissions. I'm using the JSON API, so these form submissions get posted directly to WordPress.
I've got it to display custom meta columns (e.g. first name, last name, email address) in the admin, however I now need it to show these columns in the edit page.
Note, I only need to output these columns, not have them displayed in form fields.
How do I do this? | I found the answer:
add_action('add_meta_boxes', 'add_contact_form_meta_box');
function add_contact_form_meta_box() {
add_meta_box('contact-form-meta-box-id', 'Submission Data', 'contact_form_meta_box', 'contact_form', 'normal', 'high');
}
function contact_form_meta_box($post) {
echo get_post_meta($post->ID, 'first_name', true);
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "custom post types, wp admin"
} |
how to make wordpress plugin from PersianWebToolkit?
I want to create a WordPress plugin by developing PersianWebToolkit it's a datepicker i just want to say i have a little knowledge in php i saw someone who do it but i didn't know how to do it. link of question
thank's | It sounds like you need an introduction to plugin development. As in all things WordPress Development, the WordPress Codex is the first place to look.
Here is the Plugin Development information: <
But you will need some PHP programming knowledge. Here's one good place to start: < . And the googles have plenty of information about PHP programming and tips and sample source code.
You should develop on a non-vital site - could be a testing site on your local computer, or a testing area with a WP install on your hosting site.
Good luck! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, datepicker"
} |
Excerpt is being added above the content, but it should be after it
I have this code in my functions.php file to display the excerpt of every post right below the content of every post.
But, for some reason the Excerpt is appearing above the Content when it should be below it.
Can someone show me how to make sure that the Excerpt always show up under the Content...? Thanks.
function after_post_content($content){
if (is_single()) {
$content .= the_excerpt();
}
return $content;
}
add_filter( "the_content", "after_post_content"); | You are echoing the content of the excerpt, which is being put into the header. Use `get_the_excerpt()` instead:
function after_post_content($content){
if (is_single()) {
$content .= get_the_excerpt();
}
return $content;
}
add_filter( "the_content", "after_post_content");
Generally, WordPress functions beginning with `the_` will echo the output, while functions starting will `get_the_...` will get the value. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "filters, excerpt, the content"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.